Python的内置eval()函数:
print(eval(f"3+{pow(5,3)}"))#pow()函数用于计算5的3次方
print(eval(f"3+5*3"))
结果:
128
18
我的代码:
def cul(fuc):
#接收算式
a = fuc
#添加代表结束的标识符
a += '$'
b = []
c = []
for i in a:
#判断是数字还是计算符号,这里可以用re正则表达式来进行替代
try:
if (type(float(i))) == float:
c.append(i)
except:
b.append(c)
b.append(i)
c = []
#消除末尾的”$“
b.pop()
n = 0
cul = 0
# 这段代码用于判断计算的优先度,开方>乘除>加减。
def fuc(n, cul2):
try:
p = b[n + 1]
except:return n,cul2
if p == '*' or p== '/' or p=="^":
n += 2
c = ''
l = 0
while l < len(b[n]):
j = b[n][l]
l += 1
c += j
if p == "*":
cul2 *= float(c)
elif p == "/":
cul2 /= float(c)
else:
cul2 **= float(c)
n, cul2=fuc(n,cul2)
return n,cul2
#开始计算
#先取b的长度,防止取到范围外的值
while n < len(b):
c = ''
i = b[n]
m = 0
#同上,这里判断b中每一部分的长度
while m < len(i):
j = i[m]
m += 1
c += j
#使用try来防止因为例如float(“*”)的情况导致报错退出
try:
cul = float(c)
except:
c = ''
n += 1
l = 0
#开始判断数字后的计算符号的类型,这里也可以改成上面fuc()的样子,用函数来减少代码量
if j == '+':
while l < len(b[n]):
j = b[n][l]
l += 1
c += j
cul2 = float(c)
n,cul2=fuc(n,cul2)
cul += cul2
elif j == '*':
while l < len(b[n]):
j = b[n][l]
l += 1
c += j
cul2 = float(c)
n,cul2=fuc(n,cul2)
cul *= cul2
elif j == '/':
while l < len(b[n]):
j = b[n][l]
l += 1
c += j
cul2 = float(c)
n,cul2=fuc(n,cul2)
cul /= cul2
elif j == '-':
while l < len(b[n]):
j = b[n][l]
l += 1
c += j
cul2 = float(c)
n,cul2=fuc(n,cul2)
cul -= cul2
else:
print('error')
break
n += 1
print(a.replace('$', ''), '=', cul)
运行与对比:
1.


2.

