我正在计算一个后缀表达式,我需要它来说明如果一个接一个的运算符太多,表达式就不能被计算。我知道堆栈中将没有任何内容,因此无法计算它,但我不知道如何在我的代码中添加它。
我只在这里添加了我认为是必要的代码。如果代码能保持相对相似,那就太好了。
编辑:它现在只是说任何东西都不能被评估
def process(testline,count):
k=[]
for i in range(0,len(testline),1):
if(testline[i].isdigit() == True):
k.append(float(testline[i]))
else:
try:
x = j.pop()
y = j.pop()
except IndexError:
break
if (testline[i]=='*'):
ans = x * y
k.append(ans)
elif (testline[i]=='+'):
ans = x + y
k.append(ans)
elif (testline[i]=='-'):
ans = x - y
k.append(ans)
elif (testline[i]=='/'):
ans = x / y
k.append(ans)
else:
print("Line",count,"is not able to be evaluated")
return
if len(k) != 1:
print("Line",count,"is not able to be evaluated")
else:
print ('Line',count,'result is',k[0])
return
print('Line',count,'result is',k[0])现在,输出是:
Line 1 is not able to be evaluated
Line 2 is not able to be evaluated
Line 3 is not able to be evaluated
Line 4 is not able to be evaluated输入为:
295+*3-
61*7-4*
61*79-15*
6a*7-b*
623-+*-1发布于 2019-06-30 07:18:40
您可以将您的pop移到迭代的开始处,并用try/except包围,以检查您是否可以弹出:
for i in range(0,len(testline),1):
if(testline[i].isdigit() == True):
k.append(float(testline[i]))
else:
try:
x = k.pop()
y = k.pop()
except IndexError:
break
if (testline[i]=='*'):
ans = x * y
k.append(ans)
elif (testline[i]=='+'):
ans = x + y
k.append(ans)
elif (testline[i]=='-'):
ans = x - y
k.append(ans)
elif (testline[i]=='/'):
ans = x / y
k.append(ans)
else:
print("Line",count,"is not able to be evaluated")
return为了使它更健壮,并且不需要添加那些额外的appends,我将这样做:
operators = {'*': lambda x ,y: x * y,
'/': lambda x, y: x / y,
'+': lambda x, y: x + y,
'-': lambda x, y: x - y}
for c in testline:
if c.isdigit():
k.append(float(c))
elif c in operators:
try:
x = k.pop()
y = k.pop()
except IndexError:
break
ans = operators[c](x, y)
k.append(ans)
else:
print("Line",count,"is not able to be evaluated")
return编辑:更简单:
operators = {'*': lambda x ,y: x * y,
'/': lambda x, y: x / y,
'+': lambda x, y: x + y,
'-': lambda x, y: x - y}
for c in testline:
if c.isdigit():
k.append(float(c))
else:
try:
x = k.pop()
y = k.pop()
ans = operators[c](x, y)
k.append(ans)
except IndexError: # Couldn't pop... (empty stack)
break
except KeyError: # char is not a digit and not an operator
print("Line",count,"is not able to be evaluated")
return发布于 2019-06-30 08:37:06
根据OP希望保持原始代码尽可能不变的愿望,这里有一个代码的版本,它可以用最少的更改来工作。主要的改变是在每次算术运算之前增加对操作数数量不足的检查,这也是OP特别询问的。此代码还在必要时颠倒了计算中的操作数顺序:
def process(testline,count):
k=[]
for i in range(0,len(testline),1):
if(testline[i].isdigit() == True):
k.append(float(testline[i]))
elif (testline[i]=='*'):
if len(k) < 2:
print("Line", count, "is not able to be evaluated. not enough operands")
return
x = k.pop()
y = k.pop()
ans = x * y
k.append(ans)
elif (testline[i]=='+'):
if len(k) < 2:
print("Line", count, "is not able to be evaluated. not enough operands")
return
x = k.pop()
y = k.pop()
ans = x + y
k.append(ans)
elif (testline[i]=='-'):
if len(k) < 2:
print("Line", count, "is not able to be evaluated. not enough operands")
return
x = k.pop()
y = k.pop()
ans = y - x # << reversed operands
k.append(ans)
elif (testline[i]=='/'):
if len(k) < 2:
print("Line", count, "is not able to be evaluated. not enough operands")
return
x = k.pop()
y = k.pop()
ans = y / x # << reversed operands
k.append(ans)
else:
print("Line",count,"is not able to be evaluated")
return
if len(k) != 1:
print("Line",count,"is not able to be evaluated")
return
print('Line',count,'result is',k[0])使用此测试代码:
lines = [
'295+*3-',
'61*7-4*',
'61*79-15*',
'6a*7-b*',
'(-1)*2',
'623-+*-1',
]
for i in range(len(lines)):
process(lines[i], i + 1)结果输出为:
('Line', 1, 'result is', 25.0)
('Line', 2, 'result is', -4.0)
('Line', 3, 'is not able to be evaluated')
('Line', 4, 'is not able to be evaluated')
('Line', 5, 'is not able to be evaluated')
('Line', 6, 'is not able to be evaluated. not enough operands')发布于 2019-06-30 15:39:15
这是我的版本,它很像@Tomrikoo的第二个版本,但提供了一个完整的答案,并解决了原始代码中的一些额外问题。这段代码在所有情况下都会打印结果或错误,并在有效答案或无效堆栈条件(堆栈上有多个项)的情况下处理最终状态。另外,我颠倒了操作数的应用顺序(我假设'42/‘应该产生2,而不是像我所有的HP计算器那样产生0.5 ):
def process(testline, count):
operations = {
'+': lambda x, y: y + x,
'-': lambda x, y: y - x,
'*': lambda x, y: y * x,
'/': lambda x, y: y / x,
}
k = []
for c in testline:
if c.isdigit():
k.append(float(c))
elif c in operations:
if len(k) < 2:
print("Line {}: bad expression '{}' (not enough operands)".format(count, testline))
return
k.append(operations[c](k.pop(), k.pop()))
else:
print("Line {}: unexpected character '{}' in expression '{}'".format(count, c, testline))
return
if len(k) != 1:
print("Line {}: bad expression '{}' (too many operands)".format(count, testline))
else:
print("Line {}: Result: '{}' = {}".format(count, testline, k[0]))
lines = [
'295+*3-',
'61*7-4*',
'61*79-15*',
'6a*7-b*',
'(-1)*2',
'623-+*-1',
]
for i in range(len(lines)):
process(lines[i], i + 1)输出:
Line 1: Result: '295+*3-' = 25.0
Line 2: Result: '61*7-4*' = -4.0
Line 3: bad expression '61*79-15*' (too many operands)
Line 4: unexpected character 'a' in expression '6a*7-b*'
Line 5: unexpected character '(' in expression '(-1)*2'
Line 6: bad expression '623-+*-1' (not enough operands)https://stackoverflow.com/questions/56821370
复制相似问题