问题遇到的现象和发生背景
python计算表达式程序,加入一个检查输入表达式是否有误的功能和循环运行功能应该怎么写
如:
input expresion:
-2*(3+5)+2^3/4=
-14
continue or not(y,n)?
y
input expression:
2 3 5+6=
Hint:the expression is wrong in format.
遇到的现象和发生背景,请写出第一个错误信息
用代码块功能插入代码,请勿粘贴截图。 不用代码块回答率下降 50%
import re
express = input("input expression:")
def caculator(eq):
format_list = eq_format(eq) # 把字符串变成格式化列表形式
s_eq = simplify(format_list) # 去括号,得到无括号的一个格式化列表
ans = calculate(s_eq) # 计算最终结果
if len(ans) == 2: # 判断最终结果为正数还是负数
ans = -float(ans[1])
else:
ans = float(ans[0])
return ans
def eq_format(eq):
format_list = re.findall('[\d.]+|\(|\+|-|\*|/|\)', eq)
return format_list
def simplify(format_list):
bracket = 0 # 用于存放左括号在格式化列表中的索引
count = 0
for i in format_list:
if i == '(':
bracket = count
elif i == ')':
temp = format_list[bracket + 1: count]
new_temp = calculate(temp)
format_list = format_list[:bracket] + new_temp + format_list[count + 1:]
format_list = change(format_list, bracket) # 解决去括号后会出现的-- +- 问题
return simplify(format_list) # 递归去括号
count = count + 1
return format_list
def calculate(s_eq):
if '*' or '/' in s_eq:
s_eq = remove_multiplication_division(s_eq)
if '+' or '-' in s_eq:
s_eq = remove_plus_minus(s_eq)
return s_eq
def remove_multiplication_division(eq):
count = 0
for i in eq:
if i == '*':
if eq[count + 1] != '-':
eq[count - 1] = float(eq[count - 1]) * float(eq[count + 1])
del (eq[count])
del (eq[count])
elif eq[count + 1] == '-':
eq[count] = float(eq[count - 1]) * float(eq[count + 2])
eq[count - 1] = '-'
del (eq[count + 1])
del (eq[count + 1])
eq = change(eq, count - 1)
return remove_multiplication_division(eq)
elif i == '/':
if eq[count + 1] != '-':
eq[count - 1] = float(eq[count - 1]) / float(eq[count + 1])
del (eq[count])
del (eq[count])
elif eq[count + 1] == '-':
eq[count] = float(eq[count - 1]) / float(eq[count + 2])
eq[count - 1] = '-'
del (eq[count + 1])
del (eq[count + 1])
eq = change(eq, count - 1)
return remove_multiplication_division(eq)
count = count + 1
return eq
def remove_plus_minus(eq):
count = 0
if eq[0] != '-':
sum = float(eq[0])
else:
sum = 0.0
for i in eq:
if i == '-':
sum = sum - float(eq[count + 1])
elif i == '+':
sum = sum + float(eq[count + 1])
count = count + 1
if sum >= 0:
eq = [str(sum)]
else:
eq = ['-', str(-sum)]
return eq
def change(eq, count):
if eq[count] == '-':
if eq[count - 1] == '-':
eq[count - 1] = '+'
del eq[count]
elif eq[count - 1] == '+':
eq[count - 1] = '-'
del eq[count]
return eq
result = caculator(express)
print(result)
if __name__ == '__main__':
flag=True
while (flag):
judge = input("continue or not(y,n)?")
if (judge == "n"):
print('end')
elif (judge == "y"):
express = input("input expression:")
运行结果及详细报错内容
我的解答思路和尝试过的方法,不写自己思路的,回答率下降 60%
我想要达到的结果,如果你需要快速回答,请尝试 “付费悬赏”
希望最后运行界面大概如下,如果表达式格式有误会提示
input expresion:
-2*(3+5)+2^3/4=
-14
continue or not(y,n)?
y
input expression:
2 3 5+6=
Hint:the expression is wrong in format.