代码第14天第2部分问世时我的代码有什么错误?

时间:2018-12-15 04:21:28

标签: python

我正在学习如何在python中进行编码,因此我正面临着出现代码的挑战,因此在第14天第2部分中出现错误,它说内存错误,我必须找到846601的答案,才能看看问题在问https://adventofcode.com/2018/day/14是什么,隐藏的第二部分请看这里:http://prntscr.com/lv703p

所以对于我正在使用的代码

recipe = ["3","7"]
position1 = 1
position2 = 0
value = 0
while value== 0:
    newrecipe = str(int(recipe[position2])+int(recipe[position1]))
    if len(newrecipe)== 1:
        recipe.append(newrecipe)
    elif len(newrecipe)== 2:
        recipe.append(newrecipe[0])
        recipe.append(newrecipe[1])
    position2= (position2 + int(recipe[position2])+1) % (len(recipe))
    position1= (position1 + int(recipe[position1])+1) % (len(recipe))
    if int(recipe[len(recipe)-6]) == 8:
        if int(recipe[len(recipe)-5]) == 4:
            if int(recipe[len(recipe)-4]) == 6:
                if int(recipe[len(recipe)-3]) == 6:
                    if int(recipe[len(recipe)-2]) == 0:
                        if int(recipe[len(recipe)-1]) == 1:

                            value = len(recipe)-5
print(value)

如果您有任何输入或疑问,如果我的代码令人困惑,您可以提问。

编辑: 因此,使用注释将代码更改为:

recipe = ["3","7"]
position1 = 1
position2 = 0
value=0
while value == 0:
    newrecipe = str(int(recipe[position2])+int(recipe[position1]))
    if len(newrecipe)== 1:
        recipe.append(newrecipe)
    elif len(newrecipe)== 2:
        recipe.append(newrecipe[0])
        recipe.append(newrecipe[1])
    position2= (position2 + int(recipe[position2])+1) % (len(recipe))
    position1= (position1 + int(recipe[position1])+1) % (len(recipe))
    if len(recipe) >= 6 and recipe[-6:] == ["8", "4", "6", "6", "0", "1"]:
        value= len(recipe)-5
print(value)

2 个答案:

答案 0 :(得分:0)

以...开头的语句序列

if int(recipe[len(recipe)-6]) == 8:
如果len(recipe)小于6,可能会导致

错误。您可以将整个序列替换为类似的

if len(recipe) >= 6 and recipe[-6:] == ["8", "4", "6", "6", "0", "1"]:
    ...

答案 1 :(得分:0)

我意识到错误是,一旦在配方列表中将其更改为整数,我可以使用的最大字符串限制就不会等于该值。感谢您的帮助。