gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:17:27 24 4
gpt4 key购买 nike

我正在学习 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com