diff --git a/Python/dijkstras_two_stack_algorithm.py b/Python/dijkstras_two_stack_algorithm.py new file mode 100644 index 00000000..b14ad78b --- /dev/null +++ b/Python/dijkstras_two_stack_algorithm.py @@ -0,0 +1,49 @@ +import operator as op + +from .stack import Stack + + +def dijkstras_two_stack_algorithm(equation: str) -> int: + """ + DocTests + >>> dijkstras_two_stack_algorithm("(5 + 3)") + 8 + >>> dijkstras_two_stack_algorithm("((9 - (2 + 9)) + (8 - 1))") + 5 + >>> dijkstras_two_stack_algorithm("((((3 - 2) - (2 + 3)) + (2 - 4)) + 3)") + -3 + :param equation: a string + :return: result: an integer + """ + operators = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} + + operand_stack: Stack[int] = Stack() + operator_stack: Stack[str] = Stack() + + for i in equation: + if i.isdigit(): + + operand_stack.push(int(i)) + elif i in operators: + + operator_stack.push(i) + elif i == ")": + + opr = operator_stack.peek() + operator_stack.pop() + num1 = operand_stack.peek() + operand_stack.pop() + num2 = operand_stack.peek() + operand_stack.pop() + + total = operators[opr](num2, num1) + operand_stack.push(total) + + + return operand_stack.peek() + + +if __name__ == "__main__": + equation = "(5 + ((4 * 2) * (2 + 3)))" + # answer = 45 + print(f"{equation} = {dijkstras_two_stack_algorithm(equation)}")