Python表达式化简程序无输出及TypeError问题求助
问题解决:表达式计算程序的报错与无输出问题
先解决当前的TypeError报错
第46行的operatorlo = equation.index[i]是语法错误:index是列表的方法,必须用括号调用,正确写法是:
operatorlo = equation.index(i)
代码里的其他关键问题及修复
1. lastvalue函数的语法错误
原函数里的b(len)是错误写法,获取列表长度要用len(b),修复后:
def lastvalue(a, b): if a == len(b) - 1: lastvaluevar = True else: lastvaluevar = False return lastvaluevar
注意:调用该函数时要传索引值而非元素本身,原代码传运算符元素i是错误的,需改用enumerate遍历索引和元素。
2. matchoperator函数的逻辑与调用错误
原调用matchoperator('*' and '/', equation)无效,'*' and '/'会返回'/',无法同时检查两个运算符。修改函数为检查列表中是否存在指定的任意运算符:
def matchoperator(operators, b): return any(item in operators for item in b)
调用时传入运算符列表:matchoperator(['*', '/'], equation)
3. operatorbefore函数的逻辑错误
原函数条件写法错误,且传入的pos1是数值而非索引,完全不符合逻辑。如果要检查当前运算符前后是否有乘除,改为用索引判断:
def operatorbefore(idx, list1, check_ops): if idx > 0 and list1[idx-1] in check_ops: return True if idx < len(list1)-1 and list1[idx+1] in check_ops: return True return False
4. insert方法的参数错误
list.insert()需要两个参数:插入位置和元素,原代码equation2.insert('+')会报错,若要在末尾添加元素可用append():
equation2.append('+') equation2.append(newval)
5. 循环逻辑混乱
原代码的while与for嵌套未正确修改原列表,导致重复处理同一元素甚至死循环。改为遍历列表时处理运算符,替换原列表中的运算项,直到无乘除运算符后再处理加减。
修复后的完整代码
# 初始化变量 active = True # 控制乘除处理循环 active2 = False # 控制加减处理循环 final = 0.0 # 最终结果 def has_operator(operators, target_list): # 检查列表中是否存在指定运算符 return any(op in target_list for op in operators) # 获取并格式化输入表达式 equation = input('Equation: ') # 给运算符前后加空格,方便分割 equation = equation.replace('+', ' + ').replace('-', ' - ').replace('*', ' * ').replace('/', ' / ') equation = equation.split() # 先处理乘除运算(优先级高) while active: if not has_operator(['*', '/'], equation): active = False active2 = True break for idx, item in enumerate(equation): if item in ['*', '/']: # 获取运算符前后的数值 prev_val = float(equation[idx-1]) next_val = float(equation[idx+1]) # 计算结果 if item == '*': result = prev_val * next_val else: result = prev_val / next_val # 替换原列表中的运算项:把[prev, op, next]替换为result del equation[idx-1:idx+2] equation.insert(idx-1, str(result)) # 处理完一个运算符后跳出循环,重新遍历列表 break # 再处理加减运算 while active2: if not has_operator(['+', '-'], equation): # 如果只剩一个数值,直接输出 final = float(equation[0]) print(final) active2 = False break for idx, item in enumerate(equation): if item in ['+', '-']: prev_val = float(equation[idx-1]) next_val = float(equation[idx+1]) if item == '+': result = prev_val + next_val else: result = prev_val - next_val # 替换运算项 del equation[idx-1:idx+2] equation.insert(idx-1, str(result)) break
测试验证
输入1 + 2 / 1,程序会先计算2/1=2,再计算1+2=3,最终输出3.0。
内容的提问来源于stack exchange,提问作者user22215781
相关产品推荐
相关产品推荐

