-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.py
More file actions
107 lines (101 loc) · 3.06 KB
/
calculator.py
File metadata and controls
107 lines (101 loc) · 3.06 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
def CheckInv(input):
"""确认输入字符的合法性"""
INV=""
for i in range(0,len(input)):
if input[i] in ["+","-","*","/","^","%","(",")"," ","."]:
pass
elif input[i] in ["0","1","2","3","4","5","6","7","8","9"]:
pass
else:
INV=INV+str(input[i])+" "
return INV
def TypeCheck(object):
"""确定对象为操作符或操作数"""
try:
float(object)
return 1
except:
return 0
def Priority(char):
"""确定操作符的优先级"""
if char in ["+","-"]:
return 1
elif char in ["*","/","%"]:
return 2
elif char in ["^"]:
return 3
elif char in ["(",")"]:
return 0
def SYA(crr,L=None):
"""调度场算法"""
if L==None:
arr,brr=[],[]
for i in range(0,len(crr)):
char=crr[i]
if TypeCheck(char) == 1:
brr.append(char)
elif char in ["+","-","*","/","^","%"]:
while arr!= []:
if Priority(char) <= Priority(arr[-1]) and Priority(arr[-1]) != 3:
brr.append(arr.pop())
else:
break
arr.append(char)
elif char == "(":
arr.append(char)
elif char == ")":
while arr[-1] != "(":
brr.append(arr.pop())
arr.pop()
while arr != []:
brr.append(arr.pop())
return brr
def RPN(arr,L=None):
"""逆波兰求值"""
if L==None:
brr=[]
for i in range(0,len(arr)):
if TypeCheck(arr[i]) == 1:
brr.append(float(arr[i]))
else:
tempa,tempb=brr.pop(),brr.pop()
if arr[i] == "+":
brr.append(tempb+tempa)
elif arr[i] == "-":
brr.append(tempb-tempa)
elif arr[i] == "*":
brr.append(tempb*tempa)
elif arr[i] == "/":
brr.append(tempb/tempa)
elif arr[i] == "%":
brr.append(tempb%tempa)
elif arr[i] == "^":
brr.append(tempb**tempa)
if len(brr)==1:
return brr[0]
else:
return "ERROR"
print("一个用python3写的简单计算器")
print("支持运算符{\"+\",\"-\",\"*\",\"/\",\"%(取余)\",\"^(次方)\",\"(\",\")\"},空格将被忽略")
print("一个例子:((2+3)*2)/2^2")
while True:
print()
ORI=input("请输入算式:")
tmp,crr="",[]
if CheckInv(ORI) != "":
print("Warming! “"+str(CheckInv(ORI))+"” may crash the program")
ORI=ORI+"~" #结束符
for i in range(0,len(ORI)):
if ORI[i] in ["+","-","*","/","%","^","(",")"]:
if tmp != "":
crr.append(tmp)
tmp=""
crr.append(ORI[i])
elif ORI[i] == " ":
pass
elif ORI[i] == "~":
if tmp != "":
crr.append(tmp)
else:
tmp=tmp+ORI[i]
print("Result:"+str(RPN(SYA(crr))))