《团队-科学计算器-项目进度》
团队-科学计算器-项目进度
进度:
import
re
def
md(l,x):
a
=
l.index(x)
if
x
=
=
\'*\'
and
l[a
+
1
] !
=
\'-\'
:
k
=
float
(l[a
-
1
])
*
float
(l[a
+
1
])
elif
x
=
=
\'/\'
and
l[a
+
1
] !
=
\'-\'
:
k
=
float
(l[a
-
1
])
/
float
(l[a
+
1
])
elif
x
=
=
\'*\'
and
l[a
+
1
]
=
=
\'-\'
:
k
=
-
(
float
(l[a
-
1
])
*
float
(l[a
+
2
]))
elif
x
=
=
\'/\'
and
l[a
+
1
]
=
=
\'-\'
:
k
=
-
(
float
(l[a
-
1
])
/
float
(l[a
+
2
]))
del
l[a
-
1
], l[a
-
1
], l[a
-
1
]
l.insert(a
-
1
,
str
(k))
return
l
def
fun(s):
l
=
re.findall(
\'([\d\.]+|/|-|\+|\*)\'
,s)
sum
=
0
while
1
:
if
\'*\'
in
l
and
\'/\'
not
in
l:
md(l,
\'*\'
)
elif
\'*\'
not
in
l
and
\'/\'
in
l:
md(l,
\'/\'
)
elif
\'*\'
in
l
and
\'/\'
in
l:
a
=
l.index(
\'*\'
)
b
=
l.index(
\'/\'
)
if
a < b:
md(l,
\'*\'
)
else
:
md(l,
\'/\'
)
else
:
if
l[
0
]
=
=
\'-\'
:
l[
0
]
=
l[
0
]
+
l[
1
]
del
l[
1
]
sum
+
=
float
(l[
0
])
for
i
in
range
(
1
,
len
(l),
2
):
if
l[i]
=
=
\'+\'
and
l[i
+
1
] !
=
\'-\'
:
sum
+
=
float
(l[i
+
1
])
elif
l[i]
=
=
\'+\'
and
l[i
+
1
]
=
=
\'-\'
:
sum
-
=
float
(l[i
+
2
])
elif
l[i]
=
=
\'-\'
and
l[i
+
1
]
=
=
\'-\'
:
sum
+
=
float
(l[i
+
2
])
elif
l[i]
=
=
\'-\'
and
l[i
+
1
] !
=
\'-\'
:
sum
-
=
float
(l[i
+
1
])
break
return
sum
def
calculate(expression):
ex
=
[]
ans
=
0
if
\'(\'
not
in
expression:
ans
=
fun(expression)
return
ans
for
i
in
range
(
len
(expression)):
if
expression[i]
=
=
\'(\'
:
ex.append(i)
#ex=[6,7]
elif
expression[i]
=
=
\')\'
:
#14
temp
=
0
sub
=
expression[ex[
len
(ex)
-
1
]
+
1
:i]
temp
=
fun(sub)
expression
=
expression[
0
:ex[
len
(ex)
-
1
]]
+
str
(temp)
+
expression[i
+
1
:
len
(expression)
+
1
]
ex.pop()
return
calculate(expression)
s
=
\'1 - 2 * ( (60-30 +(-40/5+3) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )\'
print
(
1
-
2
*
( (
60
-
30
+
(
-
40
/
5
+
3
)
*
(
9
-
2
*
5
/
3
+
7
/
3
*
99
/
4
*
2998
+
10
*
568
/
14
))
-
(
-
4
*
3
)
/
(
16
-
3
*
2
) ))
#1735397.4095238098
s3
=
\'3*(4+50)-((100+40)*5/2-3*2*2/4+9)*(((3+4)-4)-4)\'
#518.0
print
(
3
*
(
4
+
50
)
-
((
100
+
40
)
*
5
/
2
-
3
*
2
*
2
/
4
+
9
)
*
(((
3
+
4
)
-
4
)
-
4
))
print
(calculate(s))
#1735397.4095238098
print
(calculate(s3))
在实现一个简单的计算器中:我们要注意的问题有很多。
一、加减乘除在什么时候开始计算
二、不带括号的计算
计算乘除,在计算加减,计算一个最小计算单元后,再将结果放回列表中不断循环,直到算出整个不带括号的表达式
代码写到这里主要的功能实现了,但是上面的代码还有一个小问题,那就是如果我们的表达式如果是这样的 7*((1-4)-4) 我们按照程序流程执行的话执行一次fun的话,表达式变成这样 7*(-3-4),在执行一次的话就变成 7*-7,这样的话,我们在执行上面的fun函数就会出现问题,
1:定义最小的乘除运算单元,l是列表,x代表*或/:
2:首先获取乘除运算符的位置
3:如果是*则执行乘法运算
4:获取乘法运算的结果,比如k=3*2
5:删除掉列表里刚做运算的三个元素,比如,3 * 2
6:将刚计算的结果插入到列表中然后执行下一次计算
三、带有括号的计算
计算最里面一个括号里的表达式,调用fun函数计算出其值,将其结果代替其括号,然后不停的递归调用直到获取最后的结果
1:存储\'(\’出现的位置
2:#保存结果
3:#如果括号都处理完成了,直接调用fun函数返回结果