Skip to content

Adding in the evaluate postfix notation using Stack #2598

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

Merged
merged 12 commits into from
Oct 16, 2020
35 changes: 24 additions & 11 deletions data_structures/stacks/evaluate_postfix_notations.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
'''
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is called a docstring which explains the intent of this file. The docstring is used by pydoc if you run the command python3 -m pydoc data_structures/stacks/evaluate_postfix_notations.py

By converting this to a comment, this PR would remove that documentation.

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):
"""
>>> array = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
>>> evaluate_postfix(array)
22
>>> array = ["2", "1", "+", "3", "*"]
>>> evaluate_postfix(array)
9
>>> array = ["4", "13", "5", "/", "+"]
>>> evaluate_postfix(array)
6
>>> array = []
>>> evaluate_postfix(array)
0
"""
operations = {'+', '-', '*', '/'}
stack = []

Expand All @@ -26,10 +38,11 @@ def evaluate_postfix(postfix_notation):
stack.append(a // b)
else:
stack.append(int(token))
return stack.pop()

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

assert evaluate_postfix(
["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]) == 22
assert evaluate_postfix(["2", "1", "+", "3", "*"]) == 9
assert evaluate_postfix(["4", "13", "5", "/", "+"]) == 6

if __name__ == "__main__":
import doctest

doctest.testmod()