From 7d84f7fe61626396b2b64f3efa3fe2b740894289 Mon Sep 17 00:00:00 2001 From: Akash G Krishnan Date: Sat, 17 Oct 2020 00:15:26 +0530 Subject: [PATCH] Adding in the evaluate postfix notation using Stack (#2598) * Create evaluate_postfix_notations.py Adding in the evaluate postfix notation using Stacks one of the common use with simple stack question creating a new file for the data structure of stacks * Create evaluate_postfix_notations.py Adding in the evaluate postfix notation using Stacks one of the common use with simple stack question creating a new file for the data structure of stacks * Delete evaluate_postfix_notations.py * Evaluate postfix expression stack clean approach Sending in the PR again as the Previous request failed in pre commit * Update evaluate_postfix_notations.py * Update evaluate_postfix_notations.py Made changes as per the required for fixing the failing pre-commits. * Update evaluate_postfix_notations.py Made changes as suggested by @cclauss * Update evaluate_postfix_notations.py fixed pre-commit fails * Update evaluate_postfix_notations.py fixing pre-commit fails * Update evaluate_postfix_notations.py Deleted trailing white spaces causing pre-commits to fail * Update data_structures/stacks/evaluate_postfix_notations.py Co-authored-by: Christian Clauss * Update data_structures/stacks/evaluate_postfix_notations.py Co-authored-by: Christian Clauss Co-authored-by: Christian Clauss --- .../stacks/evaluate_postfix_notations.py | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 data_structures/stacks/evaluate_postfix_notations.py diff --git a/data_structures/stacks/evaluate_postfix_notations.py b/data_structures/stacks/evaluate_postfix_notations.py new file mode 100644 index 0000000..a03cb43 --- /dev/null +++ b/data_structures/stacks/evaluate_postfix_notations.py @@ -0,0 +1,49 @@ +""" +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: list) -> int: + """ + >>> evaluate_postfix(["2", "1", "+", "3", "*"]) + 9 + >>> evaluate_postfix(["4", "13", "5", "/", "+"]) + 6 + >>> evaluate_postfix([]) + 0 + """ + if not postfix_notation: + return 0 + + operations = {"+", "-", "*", "/"} + stack = [] + + for token in postfix_notation: + if token in operations: + b, a = stack.pop(), stack.pop() + if token == "+": + stack.append(a + b) + elif token == "-": + stack.append(a - b) + elif token == "*": + stack.append(a * b) + else: + if a * b < 0 and a % b != 0: + stack.append(a // b + 1) + else: + stack.append(a // b) + else: + stack.append(int(token)) + + return stack.pop() + + +if __name__ == "__main__": + import doctest + + doctest.testmod() -- GitLab