Created
May 16, 2017 02:03
-
-
Save rjeli/bbe3eec2025b9f7e26c8b9cb2f950bc2 to your computer and use it in GitHub Desktop.
Revisions
-
rjeli created this gist
May 16, 2017 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal 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)