Skip to content

Instantly share code, notes, and snippets.

@rjeli
Created May 16, 2017 02:03
Show Gist options
  • Select an option

  • Save rjeli/bbe3eec2025b9f7e26c8b9cb2f950bc2 to your computer and use it in GitHub Desktop.

Select an option

Save rjeli/bbe3eec2025b9f7e26c8b9cb2f950bc2 to your computer and use it in GitHub Desktop.

Revisions

  1. rjeli created this gist May 16, 2017.
    40 changes: 40 additions & 0 deletions pemdas.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    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)