-
Notifications
You must be signed in to change notification settings - Fork 0
/
infix_to_prefix_convertion_by_python .py
68 lines (53 loc) · 1.78 KB
/
infix_to_prefix_convertion_by_python .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
def isOperator(c):
return (not (c >= 'a' and c <= 'z') and not(c >= '0' and c <= '9') and not(c >= 'A' and c <= 'Z'))
def getPriority(C):
if (C == '-' or C == '+'):
return 1
elif (C == '*' or C == '/'):
return 2
elif (C == '^'):
return 3
return 0
def infixToPrefix(infix):
operators = []
operands = []
for i in range(len(infix)):
if (infix[i] == '(' ):
operators.append(infix[i])
elif (infix[i] == ')'):
while (len(operators)!=0 and (operators[-1] != '(' )):
op1 = operands[-1]
operands.pop()
op2 = operands[-1]
operands.pop()
op = operators[-1]
operators.pop()
tmp = op + op2 + op1
operands.append(tmp)
operators.pop()
elif (not isOperator(infix[i])):
operands.append(infix[i] + "")
else:
while (len(operators)!=0 and getPriority(infix[i]) <= getPriority(operators[-1])):
op1 = operands[-1]
operands.pop()
op2 = operands[-1]
operands.pop()
op = operators[-1]
operators.pop()
tmp = op + op2 + op1
operands.append(tmp)
operators.append(infix[i])
while (len(operators)!=0):
op1 = operands[-1]
operands.pop()
op2 = operands[-1]
operands.pop()
op = operators[-1]
operators.pop()
tmp = op + op2 + op1
operands.append(tmp)
return operands[-1]
while(1):
s = input("Infix Expression : ")
print("Prefix Expression : ", infixToPrefix(s))