Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanplopes/4f8fce9bc5efe847d593 to your computer and use it in GitHub Desktop.
Save juanplopes/4f8fce9bc5efe847d593 to your computer and use it in GitHub Desktop.
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