Skip to content

Instantly share code, notes, and snippets.

@anandkunal
Created March 10, 2010 06:09
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 anandkunal/327582 to your computer and use it in GitHub Desktop.
Save anandkunal/327582 to your computer and use it in GitHub Desktop.
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