-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathinfix-to-postfix.py
85 lines (66 loc) · 2.07 KB
/
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
# Copyright (C) Deepali Srivastava - All Rights Reserved
# This code is part of DSA course available on CourseGalaxy.com
from StackArray import Stack
def infix_to_postfix(infix):
postfix = ""
st = Stack()
for symbol in infix:
if symbol == ' ' or symbol == '\t': #ignore blanks and tabs
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: #operand
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)
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) )