-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpr.py
More file actions
77 lines (74 loc) · 2.42 KB
/
Copy pathexpr.py
File metadata and controls
77 lines (74 loc) · 2.42 KB
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
from stack import Stack
func_map = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y
}
def cacl(expr):
stack = Stack()
d = []
[d.append(x) for x in expr]
for idx, c in enumerate(expr):
if c in '(+-*/':
stack.push(c)
elif c.strip() == '':
pass
else:
if stack.top is None:
c = int(c)
stack.push(c)
continue
if c != ')':
c = int(c)
try:
dd = d[idx+1]
except IndexError as e:
pass
if dd in '*/':
stack.push(c)
else:
if stack.top.value in '+-*/':
s = stack.pop()
if not isinstance(stack.top.value, (int, float)):
raise Exception('wrong expr')
v = stack.pop()
v = func_map[s](v, c)
if stack.top.value in '*/':
s = stack.pop()
v2 = stack.pop()
v = func_map[s](v2, v)
stack.push(v)
else:
stack.push(c)
if c == ')':
if isinstance(stack.top.value, (int, float)):
v = stack.pop()
if stack.top.value == '(':
stack.pop()
stack.push(v)
else:
raise Exception('wrong expr')
else:
raise Exception('wrong expr')
while stack.top:
c = stack.pop()
if not isinstance(c, (int, float)):
raise Exception('wrong expr')
if stack.top is None:
return c
else:
if stack.top.value in '+-*/':
s = stack.pop()
if not isinstance(stack.top.value, (int, float)):
raise Exception('wrong expr')
v = stack.pop()
v = func_map[s](v, c)
if stack.top is None:
return v
stack.push(v)
else:
raise Exception('wrong expr')
if __name__ == '__main__':
#print(cacl('(3 + 4) * 5 / ((2 + 3) * 3)'))
#print(cacl('3+4*5*6-3-2*5-9'))