-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathevaluate.py
More file actions
91 lines (76 loc) · 2.92 KB
/
evaluate.py
File metadata and controls
91 lines (76 loc) · 2.92 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
import re
from decimal import Decimal
class Calculator(object):
def evaluate(self, string):
string_old = (re.split(' ', string))
string_new = []
for item in string_old:
if item not in '+-*/':
string_new.append(Decimal(item))
else:
string_new.append(item)
def index(lis, val):
try:
return lis.index(val)
except ValueError:
return None
def math(exp, op):
if op == '*':
return exp[0] * exp[1]
elif op == '/':
return exp[0] / exp[1]
elif op == '+':
return exp[0] + exp[1]
elif op == '-':
return exp[0] - exp[1]
def operate(temp):
if len(temp) == 1:
return temp[0]
if index(temp, '*') and index(temp, '/'):
op = min(index(temp, '*'), index(temp, '/'))
ans = math([temp[op-1], temp[op+1]], temp[op])
del temp[op-1:op+2]
temp.insert(op-1, ans)
operate(temp)
elif index(temp, '*'):
op = index(temp, '*')
ans = math([temp[op-1], temp[op+1]], temp[op])
del temp[op-1:op+2]
temp.insert(op-1, ans)
operate(temp)
elif index(temp, '/'):
op = index(temp, '/')
ans = math([temp[op - 1], temp[op + 1]], temp[op])
del temp[op-1:op+2]
temp.insert(op - 1, ans)
operate(temp)
elif index(temp, '+') and index(temp, '-'):
op = min(index(temp, '+'), index(temp, '-'))
ans = math([temp[op-1], temp[op+1]], temp[op])
del temp[op-1:op+2]
temp.insert(op-1, ans)
operate(temp)
elif index(temp, '+'):
op = index(temp, '+')
ans = math([temp[op-1], temp[op+1]], temp[op])
del temp[op-1:op+2]
temp.insert(op-1, ans)
operate(temp)
elif index(temp, '-'):
op = index(temp, '-')
ans = math([temp[op - 1], temp[op + 1]], temp[op])
del temp[op-1:op+2]
temp.insert(op - 1, ans)
operate(temp)
operate(string_new)
return float(string_new[0])
if __name__ == '__main__':
calc = Calculator()
print(calc.evaluate(string='127'))
print(calc.evaluate(string='2 + 3'))
print(calc.evaluate(string='2 - 3 - 4'))
print(calc.evaluate(string='10 * 5 / 2'))
print(calc.evaluate(string='2 / 2 + 3 * 4 - 6'))
print(calc.evaluate(string='2 + 3 * 4 / 3 - 6 / 3 * 3 + 8'))
print(calc.evaluate(string='1.1 + 2.2 + 3.3'))
print(calc.evaluate(string='1.1 * 2.2 * 3.3'))