Skip to content

Instantly share code, notes, and snippets.

@tormaroe
Created May 3, 2011 11:15
Show Gist options
  • Select an option

  • Save tormaroe/953175 to your computer and use it in GitHub Desktop.

Select an option

Save tormaroe/953175 to your computer and use it in GitHub Desktop.
class Stack_calc(object):
'''Stack calulator'''
def __init__(self):
self.item = []
self.calculate =
{'+' : lambda: self.item.append(self.item.pop() + self.item.pop()),
'-' : lambda: self.item.append(self.item.pop() - self.item.pop()),
'*' : lambda: self.item.append(self.item.pop() * self.item.pop()),
'/' : lambda: self.item.append(self.item.pop() / self.item.pop())}
def parse_stack(self, source):
self.stack = source.split()
for num in self.stack:
try:
self.item.append(float(num))
except ValueError:
for element in self.stack:
if element in ['+','-','*','/'] and len(self.item) > 1:
self.calculate[element]()
else:
try:
d = {'+': self.item[0] + self.item[0],'-': self.item[0] - self.item[0],
'*': self.item[0] * self.item[0],'/': self.item[0] / self.item[0]}
if element in d:
self.item[0] = d[element]
except (IndexError,ZeroDivisionError):
pass
def __str__(self):
return str(self.item)
def main():
'''Enter numbers,will be added to a stack
use operators +-*/ to calculate 2 last elements
To exit type Q
'''
obj = Stack_calc()
while True:
into_stack = raw_input(':-> ')
if into_stack == 'Q':
break
obj.parse_stack("%s" % into_stack)
print obj
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment