Last active
August 29, 2015 13:56
-
-
Save globby/9336070 to your computer and use it in GitHub Desktop.
Just a random mockup of a postfix evaluator
This file contains 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 characters
from operator import * | |
def isInt(x): | |
try: | |
a = float(x) | |
b = int(a) | |
except ValueError: | |
return False | |
else: | |
return a == b | |
def Postfix(exp): | |
ops, stack = {'~':(inv,1),'!':(not_,1),'*':(mul,2),'/':(div,2),'%':(mod,2),'+':(add,2),'-':(sub,2),'&':(and_,2),'^':(xor,2),'|':(or_,2)}, [] | |
for t in exp.split(' '): | |
if all(map(lambda x:x in "1234567890.",t)): | |
stack.append(int(float(t)) if isInt(t) else float(t)) | |
else: | |
if t in ops: | |
f, n = ops[t] | |
if len(stack) >= n: | |
stack.append(f(*[stack.pop() for i in range(n)][::-1])) | |
else: | |
print "Error, pop from empty stack" | |
else: | |
print "Error, non-recognized character:",t | |
return stack[0] if len(stack) == 1 else stack |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment