forked from UTSAVS26/PyVerse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PrefixToInfix.py
37 lines (28 loc) · 986 Bytes
/
PrefixToInfix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop() if not self.empty() else None
def top(self):
return self.items[-1] if not self.empty() else None
def empty(self):
return len(self.items) == 0
def prti(prefix):
s = Stack()
# Traverse the prefix expression from right to left
for t in reversed(prefix):
if t.isalnum(): # Check if the character is an operand
s.push(t)
else: # It's an operator
operand1 = s.pop()
operand2 = s.pop()
infix_expr = f"({operand1} {t} {operand2})"
s.push(infix_expr)
infix = s.pop()
print("\nPrefix to Infix expression is...")
print(infix)
if __name__ == "__main__":
prefix_expr = input("Enter prefix expression:")
prti(prefix_expr)