Created
March 10, 2010 06:09
-
-
Save anandkunal/327582 to your computer and use it in GitHub Desktop.
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
class Stacker(object): | |
""" A minimal calculator that only supports addition/multipliction. """ | |
def __init__(self): | |
self.s = [] | |
self.ops = { | |
'+' : lambda: self.s.append(self.s.pop() + self.s.pop()), | |
'*' : lambda: self.s.append(self.s.pop() * self.s.pop()) | |
} | |
def parse(self, source): | |
tokens = source.split() | |
for token in tokens: | |
try: | |
self.s.append(int(token)) | |
except ValueError: | |
# Most likely an operator, check existence | |
if token in self.ops: | |
self.ops[token]() | |
def __str__(self): | |
return str(self.s) | |
s = Stacker() | |
s.parse("18 3 + 2 * 1 +") | |
print s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment