【发布时间】:2020-04-19 11:49:25
【问题描述】:
我有一系列这样的数字
lst = [30.25, 30.0, 19.0, 31.25, 28.25, 28.25, 29.25, 28.5, 26.5, 26.5, 25.25, 24.25, 23.75, 23.5, 20.5, 20.0, 21.75, 21.25, 21.0, 19.75, 20.0]
现在我想计算总和等于给定数字(目标)的所有此类可能组合。
我从第四眼中发现了这个非常强大的代码部分:
def subsets_with_sum(lst, target, with_replacement=False):
x = 0 if with_replacement else 1
def _a(idx, l, r, t):
if t == sum(l): r.append(l)
elif t < sum(l): return
for u in range(idx, len(lst)):
_a(u + x, l + [lst[u]], r, t)
return r
return _a(0, [], [], target)
我的目标是验证是否有 3 或 4 个(在运行代码之前选择)子列表与 lst 中的唯一项目的组合,并打印找到的三元组或四元组。
如果不是:建议 1 或 2 个值来实现目标。
PS:正如您所见,lst 由十进制小时的值组成 对于我的具体情况,我的目标是 168(一周内的小时数)
【问题讨论】:
标签: python list function sum combinations