Skip to content

Commit d350b36

Browse files
Merge pull request #65 from hruday007/main
Create dijkstras_two_stack_algorithm.py
2 parents beca753 + 1912d77 commit d350b36

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import operator as op
2+
3+
from .stack import Stack
4+
5+
6+
def dijkstras_two_stack_algorithm(equation: str) -> int:
7+
"""
8+
DocTests
9+
>>> dijkstras_two_stack_algorithm("(5 + 3)")
10+
8
11+
>>> dijkstras_two_stack_algorithm("((9 - (2 + 9)) + (8 - 1))")
12+
5
13+
>>> dijkstras_two_stack_algorithm("((((3 - 2) - (2 + 3)) + (2 - 4)) + 3)")
14+
-3
15+
:param equation: a string
16+
:return: result: an integer
17+
"""
18+
operators = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub}
19+
20+
operand_stack: Stack[int] = Stack()
21+
operator_stack: Stack[str] = Stack()
22+
23+
for i in equation:
24+
if i.isdigit():
25+
26+
operand_stack.push(int(i))
27+
elif i in operators:
28+
29+
operator_stack.push(i)
30+
elif i == ")":
31+
32+
opr = operator_stack.peek()
33+
operator_stack.pop()
34+
num1 = operand_stack.peek()
35+
operand_stack.pop()
36+
num2 = operand_stack.peek()
37+
operand_stack.pop()
38+
39+
total = operators[opr](num2, num1)
40+
operand_stack.push(total)
41+
42+
43+
return operand_stack.peek()
44+
45+
46+
if __name__ == "__main__":
47+
equation = "(5 + ((4 * 2) * (2 + 3)))"
48+
# answer = 45
49+
print(f"{equation} = {dijkstras_two_stack_algorithm(equation)}")

0 commit comments

Comments
 (0)