While 循环输出列表索引超出范围

艾科尔

我被要求编写一个代码(在 Spyder 中的 Python 3.6 上),从左到右对列表“权重”的索引求和,并确定 k 的值,这是可以添加的最大权重数。权重之和不得超过该THRESHOLD值。

这是我到目前为止想到的。

THRESHOLD = 30
weights = [4, 7, 3, 5, 6, 2, 3]
accumulative_weights = 0
k = 0

while accumulative_weights <= THRESHOLD:
    accumulative_weights = weights[k] + weights[k+1]
    k += 1

但是它输出IndexError: list index out of range. 任何想法为什么会发生这种情况?

缺口

您没有测试这种情况(这就是本例中发生的情况),在您用完数组中的元素之前,您永远不会找到超过阈值的权重总和。将您的代码修改为:

THRESHOLD = 30
weights = [4, 7, 3, 5, 6, 2, 3]
accumulative_weights = 0
k = 0

while k < len(weights)-1 and accumulative_weights <= THRESHOLD:
    accumulative_weights += weights[k] + weights[k+1]
    k += 1

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章