Last active
August 29, 2015 14:07
-
-
Save juanplopes/4f8fce9bc5efe847d593 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
OPS = { | |
'+': int.__add__, | |
'-': int.__sub__, | |
'*': int.__mul__, | |
'/': int.__div__, | |
} | |
def evaluate(expression): | |
def add(chars): | |
e = mult(chars) | |
while chars[0] in "+-": | |
e = OPS[chars.pop(0)](e, mult(chars)) | |
return e | |
def mult(chars): | |
e = primary(chars) | |
while chars[0] in "*/": | |
e = OPS[chars.pop(0)](e, mult(chars)) | |
return e | |
def primary(chars): | |
if chars[0].isdigit(): | |
result = 0 | |
while chars[0].isdigit(): | |
result *= 10 | |
result += int(chars.pop(0)) | |
return result | |
if chars[0] == '(': | |
chars.pop(0) #( | |
e = add(chars) | |
chars.pop(0) #) | |
return e | |
return add(list(expression.replace(' ', '')+'$')) | |
print evaluate('2 * ( 2 + 1 )') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment