def tokenizer(expr, tokens): termo = "" lstTermos = [] for e in expr: if e in tokens: lstTermos += [termo] if e != "=": termo = e else: termo = "" lstTermos += ["="] else: termo += e lstTermos += [termo] return lstTermos #def lexicor(eq): def dictEq(eq): side = 'left' dct = {'left':[], 'right':[]} for e in eq: if e == '=': side = 'right' else: dct[side] += [e] return dct def removeItemFromList(lst, items): for i in items: lst.remove(i) return None def organizerSides(dct): lstLeftItemsToRemove=[] lstRightItemsToRemove=[] lstLeftItems = [] lstRightItems = [] #Look at the left side and move all constants to the right side of the equal sign for e in dct['left']: if e.count('x') == 0: if (-1)*int(e)> 0: sign = '+' else: sign = '' lstRightItems += [sign+str((-1)*int(e))] lstLeftItemsToRemove += [e] removeItemFromList(dct['left'],lstLeftItemsToRemove) dct['right'] += lstRightItems #Look at the right side and move all variables to the left side of the equal sign for e in dct['right']: if e.count('x'): coeficiente = int(e.strip('x')) if (-1)*coeficiente > 0: sign = '+' else: sign = "" lstLeftItems += [sign + str((-1)*coeficiente)+'x'] lstRightItemsToRemove += [e] removeItemFromList(dct['right'], lstRightItemsToRemove) dct['left'] += lstLeftItems return dct['left'], dct['right'] equation = "7x+111=15-3x+78" #eq = tokenizer("3x+1-9x-18+44=4x-90","+-=") eq = tokenizer(equation,"+-=") print equation leftEq, rightEq = organizerSides(dictEq(eq)) print rightEq print ''.join(leftEq)+"="+''.join(rightEq) sLeft = 0.0 sRight = 0.0 for e in leftEq: sLeft += int(e.strip('x')) for e in rightEq: sRight += int(e) print str(sLeft)+"x="+str(sRight) print "x="+str(sRight)+"/"+str(sLeft) print "x=", sRight/sLeft
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question