-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
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
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 *')) |