首页 > 解决方案 > 如何循环我的定义?〜sum values直到达到限制并再次循环其余部分

问题描述

我在循环中挣扎。我有一个宽度列表(双精度或整数,没关系 - 不需要精度)。基本上我需要总和低于限制的项目数。现在它只找到第一个数字。我无法适应 while 循环,因此它将重新开始计算其余项目。此代码给出 6 作为输出,导致 sum(100,300,30,100,50,80) < limit = 850。所需的循环将执行此操作:

第一次迭代:从 0 开始直到总和达到限制:[100,300,30,100,50,80,400,120,500,75,180] -> 给 6

第二次迭代:从下一个(第一次运行的最后一个索引+1)项开始并遍历其余项:400,120,500,75,180 -> 给出 2

第三:迭代 500,75,180 -> 给 3

宽度数 = 未知

如果宽度 > 限制 -> 破坏代码

Widths = [100,300,30,100,50,80,400,120,500,75,180]

def items(nums,limit):  
    sum=0   
    for i in range(0,len(nums)):  
        sum += nums[i]
        if sum>limit-1:  
          return i

print (items(Widths,850))

我想要这样的输出:[6,2,3]

标签: pythonwhile-loopsum

解决方案


return 立即退出函数。您需要存储而不是返回,然后从那里开始。我还指出了代码中的一些注释,这应该会有所帮助。

Widths = [100,300,30,100,50,80,400,120,500,75,180]

def items(nums,limit):  
    acc = 0  #do not use sum as a variable name. it "shadows" or hides the builtin function with same name
    length = 0
    result = []
    for num in nums:  #You do not really need indexes here, so you can directly iterate on items in nums list. 
        acc += num 
        if acc >= limit: #greater than or equal to. 
            result.append(length)
            acc = num
            length = 1
        else:
            length += 1
    result.append(length) #if you need the last length even if it does not add up.
    return result


print (items(Widths,850))
#Output:
[6, 2, 3]

推荐阅读