Skip to content

Instantly share code, notes, and snippets.

@darkf
Created April 19, 2013 09:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkf/5419317 to your computer and use it in GitHub Desktop.
Save darkf/5419317 to your computer and use it in GitHub Desktop.
ugly non-non-precendence-enabled infix calculator
import operator
def evaluate(input):
ops = {'+': operator.add, '-': operator.sub, '*': operator.mul}
def e(toks, s_num, s_ops):
if toks == []:
return s_num.pop()
try:
s_num.append(float(toks[0]))
except ValueError:
s_ops.append(toks[0])
if s_ops != [] and len(s_num) >= 2:
lhs, rhs = s_num.pop(), s_num.pop()
s_num.append(ops[s_ops.pop()](lhs, rhs))
return e(toks[1:], s_num, s_ops)
return e(input.split(), [], [])
def main():
print evaluate("3 + 1 * 2")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment