python-3.x - 如何在 python 中使用 while 循环来添加列表中的值,直到它们超过最大值?

标签 python-3.x while-loop range

我正在学习 python V3,在作业中遇到以下问题:

In this exercise, your function will receive a list of numbers, and an integer. It will add the values in the list to a total as long as the total is less than or equal to the value of the second parameter. The sum of numbers in the list will always be larger than the second parameter's value.

我想出了以下解决方案:

def while11(nums,maxi):
    i=0
    total=0
    while total<=maxi:
        total+=nums[i]
    return total

测试参数如下:

[1,1,1,1,1,1,1,1,1], 6
[2,2,2,2,2,2,2,2,2], 6
range(10, 1, -1), 25

对于前两组参数,my 函数分别返回 78。但是,它应该为第三组返回 27,但它返回 30。它似乎添加了 11109 而不是 1098

最佳答案

您需要在执行计算时递增 i。

def while11(nums,maxi):
    i=0
    total=0
    while total<=maxi:
        total+=nums[i]
        i+=1
    return total

您的函数只是获取列表中的第一个值并添加它,直到它大于最大值。您可能没有注意到这一点,因为在前两种情况下,所有值都相同。但是,在第三种情况下,您有一个由 [10、9、8、7、6、5、4、3、2] 组成的列表。这应该采用 10 + 9 + 8 + 7... 等直到最大值,但是您的函数采用 10 + 10 + 10 + 10 ... 等直到最大值。

关于python-3.x - 如何在 python 中使用 while 循环来添加列表中的值,直到它们超过最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39985958/

相关文章:

python - 有人可以解释一下这里提到的策略元类的目的吗

python-3.x - 计算完整图中的距离度量

c++ - 如何跳出循环?

c - 在 while(1) 循环中等待用户输入

python - 重新排序列表,尽可能使所有先前数字的总和小于当前数字

python - 如何在 SymPy 中收集分数?

php - 有没有办法避免最后出现空的 else { }?

swift - 如何从一个范围内的数字插值到另一个范围内的相应值?

c++ - boost 范围 weak_ptr

javascript - jQuery HTML5 范围 slider 中的实时输出