forked from UTSAVS26/PyVerse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InfixToPrefix.py
64 lines (52 loc) · 1.46 KB
/
InfixToPrefix.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def prec(c):
if c in ['+', '-']:
return 1
if c in ['*', '/']:
return 2
return 0
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 itpr(infix):
s1 = Stack() # Stack for operands
s2 = Stack() # Stack for operators
j = 0
prefix = []
for i in range(len(infix) - 1, -1, -1):
t = infix[i]
if t.isalnum():
s1.push(t)
elif t == ')':
s2.push(')')
elif t == '(':
x = s2.pop()
s1.push(x)
else:
if s2.empty():
s2.push(t)
else:
x = s2.pop()
s1.push(x)
s2.push(t)
while not s2.empty():
x = s2.pop()
s1.push(x)
while not s1.empty():
x = s1.pop()
if x != ')':
prefix.append(x)
prefix.append('\0') # To indicate the end, if needed
prefix_str = ''.join(prefix[:-1]) # Exclude the '\0'
print("\nPrefix expression is...")
print(prefix_str)
if __name__ == "__main__":
infix_expr = input("Enter infix expression: ")
itpr(infix_expr)