该程序应该将所有可除以3和5的数字添加在一起,但我不明白,我尝试运行此脚本,它只是继续给我错误:
Traceback (most recent call last):
File "first.py", line 23, in <module>
main()
File "first.py", line 19, in main
merica = merica + good[count-1]
IndexError: list index out of range
我不明白这意味着什么,因为
count-1
在索引范围内,看起来对吗?
def main():
merica = 0
commonfactors = []
good = []
count = 1
while count <= 1000:
if count%3 == 0:
good.append(count)
elif count%5 == 0:
if count in good:
commonfactors.append(count)
else:
good.append(count)
count = count+1
count = count - 1000
while count <= 1000:
merica = merica + good[count-1]
count = count+1
print(merica)
main()
exit()
任何帮助都非常感谢!
当计数为3或5(不是两者)时,您仅将数字附加到好。
所以,好的大小不会是1000。
这就是为什么您会遇到错误。
您的下面循环只能运行到计数&lt; = 466。
def main():
merica = 0
commonfactors = []
good = []
count = 1
while count <= 1000:
if count%3 == 0:
good.append(count)
elif count%5 == 0:
if count in good:
commonfactors.append(count)
else:
good.append(count)
count = count+1
count = count - 1000
while count <= len(good):
merica = merica + good[count-1]
count = count+1
print(merica)
main()
exit()
由于错误说列表索引超出了范围,所以让我们考虑列表的时间多长时间以及我们尝试使用的索引。在这里,假设列表good
中有1000个项目,因为while循环最高为1000。
while count <= 1000:
merica = merica + good[count-1]
count = count+1
好吧,所以现在我们看到该程序期望列表中有1000个项目。让我们看看当我们构建列表时,这是否成立。
while count <= 1000:
if count%3 == 0:
good.append(count)
elif count%5 == 0:
if count in good:
commonfactors.append(count)
else:
good.append(count)
count = count+1
现在,我们看到列表是通过将值从1到1000添加到其上的值来构造的。但是,我们应用条件来附加它,也就是说,必须由3或5分开。那么什么关于素数?附加这些数字没有else
块。因此,我们不附加完整的1000个数字,但仅将这些数字添加为5或3。
解决方案是改变我们对第二个环路大小的假设。while count <= len(good):
将根据列表的大小调整长度。
整个块都假设good
的长度不准确。
while count <= 1000:
merica = merica + good[count-1]
count = count+1
如果您仅在其中放置子集,则长度不能为1000。
无论如何,您应该了解内置的sum()
功能:
good = [1, 2, 3]
merica = sum(good)
您也可能会发现range()
功能也有帮助:
for number in range(1000):
# This will loop 1000 times with number equal to 0 to 999.
这将变成代码评论...但是您为什么要这样做:
count = count - 1000
而不仅仅是设置count = 0
?
您还可以从一些更具防御风格的编程中受益。了解如何使用assert
:
count = count - 1000
assert count == 0
和
assert count-1 < len(good)
merica = merica + good[count-1]
这些断言将帮助您快速追踪您正在做出的假设。
祝你好运!