我正试着做这个polish notation challenge on kattis.com。问题是,我觉得我已经完成了他们要求的一切,并且我已经试着修复我能想到的一切。我甚至查阅了一些其他人的解决方案,虽然他们的解决方案更干净,但我想在学习的过程中继续我的解决方案
为什么例如this person's code可以工作,而不是我的
这是我目前的代码:
import sys
case = 1
valid_ints = set([str(i) for i in range(-10,11)])
def simplify(index, myLine, processed):
while index+1 > 0:
if (myLine[index] == "+" or myLine[index] == "-" or myLine[index] == "*") and index < len(myLine)-2:
if myLine[index+1] in valid_ints and myLine[index+2] in valid_ints:
try:
processed = myLine[index+3:] + processed
a = str(myLine[index+1] + myLine[index] + myLine[index+2])
processed.insert(0, str(eval(a)))
del myLine[index:]
except:
processed = [myLine[index], myLine[index+1], myLine[index+2]] + processed
del myLine[index:]
elif len(myLine) < 3:
processed = myLine + processed
del myLine[index]
index -= 1
processed = myLine + processed
return processed
for line in sys.stdin:
myLine = line.split()
processed = []
index = len(myLine)-1
savedprocessed = []
processed = simplify(index, myLine, processed)
while True:
if savedprocessed == processed:
break
else:
savedprocessed = []
savedprocessed += processed
processed = simplify(len(processed)-1, processed, [])
result = " ".join(savedprocessed)
print("Case " + str(case) + ": " + result)
case += 1
if case > 5:
break
您正在为Python带来一些其他的语言风格,这是不必要的,因为Python更灵活
我已经尽可能地简化了
在空白处拆分输入字符串,并迭代标记
对于表达式中的每个运算符,将
list
推送到堆栈上,并将运算符及其操作数附加到list
现在将每个
list
从堆栈中弹出并处理list
产出
相关问题 更多 >
编程相关推荐