-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheasyCaculator.py
67 lines (52 loc) · 1.32 KB
/
easyCaculator.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
class Stack():
arr=[]
def __init__(self):
self.arr=[]
def push(self,element):
self.arr.insert(0,element)
def pop(self):
return self.arr.pop(0)
def peek(self):
return self.arr[0]
def size(self):
return len(self.arr)
import re
def in2post(exp):
op_priority = {
'/': 2,
'*': 2,
'+': 1,
'-': 1,
'#': 0}
op_stack= Stack()
out=[]
lst = re.findall('[\+\-\*\/]|[\d]+', exp)
op_stack.push('#')
for i in range(len(lst)):
op:str=lst[i]
if op.isdigit():
out.append(op)
else:
while op_priority.get(op)<=op_priority.get(str(op_stack.peek())):
out.append(op_stack.pop())
op_stack.push(op)
while(op_stack.size()!=0):
out.append(op_stack.pop())
return out
def calc_postfix(postfix):
"""计算后缀表达式的值。"""
stack = Stack()
for op in postfix:
if op.isdigit():
stack.push(op)
elif op=='#':
break
else:
a = float(stack.pop())
b = float(stack.pop())
stack.push(eval("{}{}{}".format(b,op,a)))
return stack.peek()
# s=input()
exp='3*9-6+3*7/5+53614-36254*3254'
a=calc_postfix(in2post(exp))
print(round(a))