-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSem6_infix_to_postfix.py
100 lines (80 loc) · 2.35 KB
/
Sem6_infix_to_postfix.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def size(self):
return len(self.items)
def push(self, item):
self.items.append(item)
def pop(self):
if self.is_empty():
raise EmptyStackError("Stack is empty")
return self.items.pop()
def peek(self):
if self.is_empty():
raise EmptyStackError("Stack is empty")
return self.items[-1]
def display(self):
print(self.items)
def infix_to_postfix(infix):
postfix = ""
st = Stack()
for symbol in infix:
if symbol == ' ' or symbol == '\t':
continue
if symbol == '(':
st.push(symbol)
elif symbol == ')':
next = st.pop()
while next != '(':
postfix = postfix + next
next = st.pop()
elif symbol in "+-*/%^":
while not st.is_empty() and precedence(st.peek()) >= precedence(symbol):
postfix = postfix + st.pop()
st.push(symbol)
else:
postfix = postfix + symbol
while not st.is_empty():
postfix = postfix + st.pop()
return postfix
def precedence(symbol):
if symbol == '(':
return 0
elif symbol in '+-':
return 1
elif symbol in '*/%':
return 2
elif symbol == '^':
return 3
else:
return 0
def evaluate_postfix(postfix):
st = Stack()
for symbol in postfix:
if symbol.isdigit():
st.push(int(symbol))
else:
x = st.pop()
y = st.pop()
if symbol == '+':
st.push(y + x)
elif symbol == '-':
st.push(y - x)
elif symbol == '*':
st.push(y * x)
elif symbol == '/':
st.push(y / x)
elif symbol == '^':
st.push(y ** x)
return st.pop()
#############
while True:
print("Enter infix expression ( q to quit ) ", end='')
expression = input()
if expression == 'q':
break
postfix = infix_to_postfix(expression)
print("Postfix expression is : ", postfix)
#print("Value of expression : ", evaluate_postfix(postfix))