forked from vivek3141/MathP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmathp_eval.py
More file actions
executable file
·131 lines (129 loc) · 2.38 KB
/
mathp_eval.py
File metadata and controls
executable file
·131 lines (129 loc) · 2.38 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def mathpevalplus(s):
a = ""
sum = 0
z = ""
c = 0
op = ""
for i in s:
if(i == "+"):
sum = sum + int(a)
a = ""
op = "+"
if(i == "-"):
sum = sum + int(a)
a = ""
op = "-"
else:
a = a + i
try:
z = s[c+1]
except IndexError:
if(op == "+"):
sum = sum + int(a)
elif(op == "-"):
sum = sum - int(a)
else:
sum = sum + int(a)
c = c + 1
return sum
def mathpeval(s):
if(s.find('*') == -1 and s.find('/') == -1 and s.find('+') == -1 and s.find('-') == -1) and ("(" in s or ")" in s):
raise SyntaxError
return False
return mathpevalbrac(s)
def mathpevalbrac(s):
st = s
z = ""
add = False
co = 0
for i in s:
if(i == "("):
z = z + i
co = co + 1
add = True
elif(i == ")" and co == 1):
add = False
break
elif(i == ")"):
z = z + i
co = co - 1
elif(add):
z = z + i
exe = z
exe = exe.replace("(","",1)
z = z + ")"
x = exe
if(exe == "" and "(" in s):
raise SyntaxError
return False
while(str(exe).find("(") != -1):
exe = mathpeval(exe)
res = mathpevalmul(exe)
st = st.replace(z,str(res),1)
if "(" in exe:
st = st.replace(z,str(res),1)
st = mathpeval(st)
else:
st = mathpevalmul(st)
return str(st)
def mathpevalmul(s):
st = s
div = []
mul = []
c = 0
for i in st:
if(i == "*"):
mul.append(c)
c = c + 1
for i in mul:
k = ""
indexm = i-1
while(indexm >= 0 and indexm < len(s)):
if not (s[indexm].isdigit()):
break
k = k + s[indexm]
indexm = indexm - 1
k = "".join(reversed(k))
indexf = i+1
v = ""
while(indexf < len(s)):
if not(s[indexf].isdigit()):
break
v = v + s[indexf]
indexf = indexf + 1
final = k + "*" + v
res = str(int(k)*int(v))
st = st.replace(final,str(res),1)
while(st.find("*") != -1):
st = str(mathpeval(st))
c = 0
for i in st:
if(i == "/"):
div.append(c)
c = c + 1
stv = st
for i in div:
k = ""
indexm = i-1
while(indexm >= 0 and indexm < len(stv)):
if not (stv[indexm].isdigit()):
break
k = k + stv[indexm]
indexm = indexm - 1
k = "".join(reversed(k))
indexf = i+1
v = ""
while(indexf < len(stv)):
if not(stv[indexf].isdigit()):
break
v = v + stv[indexf]
indexf = indexf + 1
final = k + "/" + v
if(v == "0"):
raise ZeroDivisionError
res = int(k)/int(v)
res = int(res)
st = st.replace(final,str(res),1)
while(st.find("/") != -1):
st = str(mathpeval(st))
return mathpevalplus(st)