Skip to content

Commit 796a5be

Browse files
authored
Add files via upload
1 parent ea82f9e commit 796a5be

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

shunting-yard/infix_to_postfix.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
def get_precedence(op):
2+
precedences = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
3+
return precedences.get(op, 0)
4+
5+
def infix_to_postfix(expression):
6+
output = []
7+
stack = []
8+
tokens = expression.split()
9+
10+
for token in tokens:
11+
print("Token:", token)
12+
if token.isnumeric():
13+
output.append(token)
14+
elif token == '(':
15+
stack.append(token)
16+
elif token == ')':
17+
while stack and stack[-1] != '(':
18+
output.append(stack.pop())
19+
stack.pop() # Pop the left parenthesis
20+
else:
21+
while stack and get_precedence(stack[-1]) >= get_precedence(token):
22+
output.append(stack.pop())
23+
stack.append(token)
24+
print("Output stack:", output)
25+
print("Operator stack:", stack)
26+
27+
while stack:
28+
output.append(stack.pop())
29+
30+
return ' '.join(output)
31+
32+
33+
infix_expression = input("Enter an infix expression: ")
34+
postfix_expression = infix_to_postfix(infix_expression)
35+
print("Postfix expression:", postfix_expression)

0 commit comments

Comments
 (0)