以下代码是由我在许多退伍军人的帮助下创建的:
代码采用输入的数学表达式并将其拆分为运算符和操作数以供以后使用。我创建了两个函数,分裂的解析函数和错误函数。我有错误功能的问题,因为它不会显示我的错误消息,我觉得代码运行时忽略该功能。如果输入如下表达式,则应打印错误:3 // 3 + 4等。其中有两个运算符在一起,或者整个表达式中有两个以上的运算符,但错误消息不打印。我的代码如下:
def errors():
numExtrapolation,opExtrapolation=parse(expression)
if (len(numExtrapolation) == 3) and (len(opExtrapolation) !=2):
print("Bad1")
if (len(numExtrapolation) ==2) and (len(opExtrapolation) !=1):
print("Bad2")
def parse(expression):
operators= set("*/+-")
opExtrapolate= []
numExtrapolate= []
buff=[]
for i in expression:
if i in operators:
numExtrapolate.append(''.join(buff))
buff= []
opExtrapolate.append(i)
opExtrapolation=opExtrapolate
else:
buff.append(i)
numExtrapolate.append(''.join(buff))
numExtrapolation=numExtrapolate
#just some debugging print statements
print(numExtrapolation)
print("z:", len(opExtrapolation))
return numExtrapolation, opExtrapolation
errors()
任何帮助将不胜感激。请不要引入比此处已有的代码更高级的新代码。我正在寻找我的问题的解决方案...不是大的新代码段。感谢。
答案 0 :(得分:1)
在parse()返回后调用errors()函数,因为它出现在parse()体内。希望这是一个错字。
对于此特定输入,numExtrapolate附加一个空缓冲区,因为/和/之间没有操作数。这使得它的长度为4,而你对Bad1的检查失败了。所以像这样检查
if buff:
numExtrapolate.append(''.join(buff))