-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.py
87 lines (68 loc) · 2.04 KB
/
calculator.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def solve(ans):
if(len(ans) == 0): return
num_count = 0
s = []
i = 0
while i < len(ans):
if((ans[i] >= "0" and ans[i] <= "9") or (ans[i] == ".")):
numtmp = ""
while (i < len(ans)) and ((ans[i] >= "0" and ans[i] <= "9") or (ans[i] == ".")):
numtmp += ans[i]
i += 1
i-=1
s.append(numtmp)
num_count += 1
elif (ans[i] == " "):
i += 1
continue
elif (ans[i] == "+"):
if(num_count < 2):
return "NAN"
tmp1 = s.pop()
tmp2 = s.pop()
s.append(str(float(tmp1) + float(tmp2)))
elif (ans[i] == "*"):
if(num_count < 2) :
return "NAN"
tmp1 = s.pop()
tmp2 = s.pop()
s.append(str(float(tmp1) * float(tmp2)))
num_count -= 1;
elif (ans[i] == "/"):
if(num_count < 2) :
return "NAN"
tmp1 = s.pop()
tmp2 = s.pop()
if(float(tmp1) != 0):
s.append(str(float(tmp2) / float(tmp1)))
num_count -= 1
else: return "NAN"
elif(ans[i] == "-"):
if(num_count < 2) :
return "NAN"
tmp1 = s.pop()
tmp2 = s.pop()
s.append(str(float(tmp2) - float(tmp1)))
num_count -= 1
elif(ans[i] == "%"):
if(num_count < 2) :
return "NAN"
tmp1 = s.pop()
tmp2 = s.pop()
s.append(str(float(tmp2) % float(tmp1)))
num_count -= 1
elif(ans[i] == "^"):
if(num_count < 2) :
return "NAN"
tmp1 = s.pop()
tmp2 = s.pop()
if "." in tmp1 or "." in tmp2 :
s.append(str(float(tmp2) ** float(tmp1)))
else: s.append(int(tmp2) ** int(tmp1))
num_count -= 1
i += 1
return s[-1]
def bench():
l = "2 3 +"
print(solve(l))
bench()