-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
50 lines (36 loc) · 1.03 KB
/
main.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
stack = [] # Array where operators contained
output = []
priority = {
'*': 2,
'/': 2,
'+': 1,
'-': 1
}
def infixToPrefix(data):
data = Tokenization(data)
print(data)
for i in data:
if i.isdigit():
output.append(i)
else:
stack.append(i)
if i == ')': # Appending eac elem until we reach the "("
while stack[-1] != '(':
e = stack.pop()
output.append(e)
stack.pop()
output.remove(')')
if len(stack) != 0:
for x in stack:
try:
if priority[stack[-1]] <= priority[stack[-2]]:
output.append(stack[-2])
del stack[-2]
except (IndexError, KeyError):
pass
output.append(stack[-1])
res = ' '.join(output)
return res
def Tokenization(non_token):
return list(non_token.replace(' ', ''))
print(infixToPrefix('5 * (10 - 8) / 7 + 1'))