Created
August 12, 2015 23:02
-
-
Save yosemitebandit/1c874b8b154d76418974 to your computer and use it in GitHub Desktop.
stacks in python
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
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