diff --git a/data_structures/stacks/evaluate_postfix_notations.py b/data_structures/stacks/evaluate_postfix_notations.py index 51ea353b17de..40e7da2f5c0f 100644 --- a/data_structures/stacks/evaluate_postfix_notations.py +++ b/data_structures/stacks/evaluate_postfix_notations.py @@ -17,9 +17,29 @@ def evaluate_postfix(postfix_notation: list) -> int: 9 >>> evaluate_postfix(["4", "13", "5", "/", "+"]) 6 + >>> evaluate_postfix(["2", "+"]) + 2 + >>> evaluate_postfix(["5", "-"]) + -5 >>> evaluate_postfix([]) 0 - """ + >>> evaluate_postfix(["5"]) + 5 + >>> evaluate_postfix(["5", "A"]) + Traceback (most recent call last): + ... + ValueError: invalid literal for int() with base 10: 'A' + >>> evaluate_postfix(["5", "4", "A"]) + Traceback (most recent call last): + ... + ValueError: invalid literal for int() with base 10: 'A' + >>> evaluate_postfix(["A"]) + Traceback (most recent call last): + ... + ValueError: invalid literal for int() with base 10: 'A'""" + if len(postfix_notation) == 1 and postfix_notation[0] in {"+", "-", "*", "/"}: + raise ValueError("Invalid expression: insufficient operands") + if not postfix_notation: return 0 @@ -28,18 +48,27 @@ def evaluate_postfix(postfix_notation: list) -> int: 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) + if len(stack) < 2: + operand = stack.pop() + if token == "-": + stack.append(-operand) else: + stack.append(operand) + else: + b, a = stack.pop(), stack.pop() + if token == "+": + stack.append(a + b) + elif token == "-": + stack.append(a - b) + elif token == "*": + stack.append(a * b) + elif token == "/": + if b == 0: + raise ValueError("Invalid expression: division by zero") stack.append(a // b) + else: + msg = f"Unrecognized {token = }" + raise ValueError(msg) else: stack.append(int(token))