Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding in the evaluate postfix notation using Stack #2598

Merged
merged 12 commits into from
Oct 16, 2020
Prev Previous commit
Next Next commit
Update evaluate_postfix_notations.py
Made changes as suggested by @cclauss
  • Loading branch information
akashgkrishnan authored Oct 15, 2020
commit e1c15e9a2245c283f688433bf871feca9ba8d2c7
24 changes: 13 additions & 11 deletions data_structures/stacks/evaluate_postfix_notations.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
# The Reverse Polish Nation also known as Polish postfix notation or simply postfix notation
# https://en.wikipedia.org/wiki/Reverse_Polish_notation
# Classic examples of simple stack implementations
# Valid operators are +, -, *, /. Each operand may be an integer or another expression.
"""
The Reverse Polish Nation also known as Polish postfix notation or simply postfix notation
https://en.wikipedia.org/wiki/Reverse_Polish_notation
Classic examples of simple stack implementations
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
"""


def evaluate_postfix(postfix_notation):
akashgkrishnan marked this conversation as resolved.
Show resolved Hide resolved
"""
>>> array = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
>>> evaluate_postfix(array)
>>> evaluate_postfix(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"])
22
>>> array = ["2", "1", "+", "3", "*"]
>>> evaluate_postfix(array)
>>> evaluate_postfix(["2", "1", "+", "3", "*"])
9
>>> array = ["4", "13", "5", "/", "+"]
>>> evaluate_postfix(array)
>>> evaluate_postfix(["4", "13", "5", "/", "+"])
6
>>> array = []
>>> evaluate_postfix(array)
0
"""
if not postfix_notation:
return 0

operations = {'+', '-', '*', '/'}
cclauss marked this conversation as resolved.
Show resolved Hide resolved
stack = []

Expand All @@ -39,7 +41,7 @@ def evaluate_postfix(postfix_notation):
else:
stack.append(int(token))

return stack.pop() if len(stack) != 0 else 0
return stack.pop()


if __name__ == "__main__":
Expand Down