Skip to content

Instantly share code, notes, and snippets.

@yosemitebandit
Created August 12, 2015 23:02
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 yosemitebandit/1c874b8b154d76418974 to your computer and use it in GitHub Desktop.
Save yosemitebandit/1c874b8b154d76418974 to your computer and use it in GitHub Desktop.
stacks in python
import re
class Stack(object):
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return self.items == []
def eval_postfix(expression):
"""Evaluate postfix expressions.
E.g. "3 4 + 2 *" -> 14
"""
tokens = re.split("([^0-9])", expression)
stack = Stack()
for token in tokens:
token = token.strip()
if not token:
continue
if token == '+':
result = stack.pop() + stack.pop()
stack.push(result)
elif token == '*':
result = stack.pop() * stack.pop()
stack.push(result)
else:
stack.push(float(token))
return stack.pop()
s = Stack()
s.push(3)
s.push(4)
s.push(5)
s.push(10)
print s.is_empty()
print s.pop()
print eval_postfix('23 43 + 5 *')
# 330.0
print eval_postfix('2 1 + 2 * 3 + 4 *')
# 36.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment