首页 > 解决方案 > 我的代码中出现的代码第 14 部分第 2 部分的错误是什么?

问题描述

我正在学习如何在 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)

标签: python

解决方案


开头的语句序列

if int(recipe[len(recipe)-6]) == 8:

如果低于 6,可能会导致错误len(recipe),这可能是。你可以用类似的东西替换整个序列

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

推荐阅读