python - 如何循环我的定义?〜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]
解决方案
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]
推荐阅读
- ubuntu - ping 域名添加到主机文件不起作用| ubuntu
- php - Nginx 没有错误页面显示,无论我使用什么配置
- c# - 动态左连接 2 数据表
- javascript - 是否有用于将 Bootstrap 数据父级连接到子级的 jQuery 语法
- anylogic - 在 Anylogic 中,我如何为向多个客户交付订单的卡车建模
- python - 如何重新采样并在多列上创建 value_counts() 和 count() 的时间序列?
- facebook-graph-api - Facebook Api V10:如何在我的 Facebook 帖子中标记或提及用户?
- windows - 如何使用 Chocolatey 安装特定版本的 windows sdk?
- python - 如何从python中的fbProphet中提取每个显着变化点的斜率?
- google-bigquery - 在 BigQuery 中,是否可以通过流以及批量加载同一表来摄取数据?