Skip to content

Instantly share code, notes, and snippets.

@rjeli
Created May 16, 2017 02:03
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 rjeli/bbe3eec2025b9f7e26c8b9cb2f950bc2 to your computer and use it in GitHub Desktop.
Save rjeli/bbe3eec2025b9f7e26c8b9cb2f950bc2 to your computer and use it in GitHub Desktop.
inputs = [
'1 + 1',
'2 * 2',
'1 + 2 * 3',
'( 1 + 2 ) * 3'
]
def pemdas(s):
ops = { op: p for p, l in enumerate(['+-', '*/']) for op in l }
ostk = []
out = []
for tok in s.split(' '):
if tok.isdigit():
out.append(tok)
elif tok in ops:
while ostk and ostk[-1] not in '()' and ops[tok] <= ops[ostk[-1]]:
out.append(ostk.pop())
ostk.append(tok)
elif tok == '(':
ostk.append(tok)
elif tok == ')':
while ostk[-1] != '(':
out.append(ostk.pop())
ostk.pop()
while ostk:
out.append(ostk.pop())
stk = []
for v in out:
if v.isdigit():
stk.append(int(v))
elif v in ops:
stk.append({
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y,
}[v](stk.pop(), stk.pop()))
return stk[0]
print '\n'.join(str(pemdas(i)) for i in inputs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment