-
Notifications
You must be signed in to change notification settings - Fork 0
/
artificial.py
57 lines (50 loc) · 1.4 KB
/
artificial.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
from pythonds.basic.stack import Stack
def infixtopostfix(s):
dic={"*":3,"/":3,"+":2,"-":2,"(":1}
sta = Stack()
res = []
s = list(s)
for token in s:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789":
res.append(token)
elif token=='(':
sta.push(token)
elif token==')':
tt = sta.pop()
while tt!='(':
res.append(tt)
tt=sta.pop()
else:
while (not sta.isEmpty()) and \
(dic[sta.peek()]>=dic[token]):
res.append(sta.pop())
sta.push(token)
while not sta.isEmpty():
res.append(sta.pop())
return "".join(res)
def calcualtepostfix(s):
s = list(infixtopostfix(s))
k=["+","-","*","/"]
te = Stack()
s = list(s)
for i in s:
if i not in k:
te.push(i)
elif i == "+":
r = te.pop()
l = te.pop()
te.push(str(int(l)+int(r)))
elif i == "*":
r = te.pop()
l = te.pop()
te.push(str(int(l)*int(r)))
elif i == "-":
r = te.pop()
l = te.pop()
te.push(str(int(l)-int(r)))
elif i == "/":
r = te.pop()
l = te.pop()
te.push(str(int(l)/int(r)))
return te.pop()
print(calcualtepostfix("((((5+7)-4)*6)+5)"))