python - 我的代码中出现的代码第 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)
解决方案
开头的语句序列
if int(recipe[len(recipe)-6]) == 8:
如果低于 6,可能会导致错误len(recipe)
,这可能是。你可以用类似的东西替换整个序列
if len(recipe) >= 6 and recipe[-6:] == ["8", "4", "6", "6", "0", "1"]:
...
推荐阅读
- shell - Ansible 使用 awk 提取 shell 输出
- angular - KeyCloak 在重定向时用单斜杠替换双斜杠
- python - 写入文本并保存对话框
- php - Laravel 7-从数据库中获取数据时出现未定义的偏移错误
- networking - 如何通过 WiFi 控制开关?
- python - 如何使用 GDB 调试异步协程?
- ssl - System.IO.Exception:由于意外的打包格式,握手失败
- javascript - 在 Prestashop 部分 (product.tpl) 中插入动态 Google 图表
- python - 带有Tkinter和openCV的图像编辑软件,以及如何制作一个达到功能并显示它的按钮
- python - Tkinter 登录表单