Skip to content

Commit

Permalink
Merge 1e03cd2 into 30ca4ae
Browse files Browse the repository at this point in the history
  • Loading branch information
nisaruj committed Oct 2, 2018
2 parents 30ca4ae + 1e03cd2 commit fa246bd
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions algorithms/stack/evaluate_postfix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""
Given a postfix expression, a function eval_postfix
takes a string of postfix expression and evaluates it.
Note that numbers and operators are seperated by whitespace.
For example:
eval_postfix('5 14 - 3 /') should return -3.0.
eval_postfix('-1.3 3 + 2 *') should return 3.4.
"""

def eval_postfix(expression):
stack = []
split_exp = expression.split()
for item in split_exp:
try:
stack.append(float(item))
except ValueError:
val1 = stack.pop()
val2 = stack.pop()
if item == '+':
stack.append(val2 + val1)
elif item == '-':
stack.append(val2 - val1)
elif item == '*':
stack.append(val2 * val1)
elif item == '/':
stack.append(val2 / val1)
return stack.pop()

print(eval_postfix('5 14 - 3 /'))
print(eval_postfix('-1.3 3 + 2 *'))

0 comments on commit fa246bd

Please sign in to comment.