生成组合,使总数始终为 100 并使用定义的跳跃值
Generate combinations such that the total is always 100 and uses a defined jump value
我希望生成一个组合列表,使总数始终为 100。必须根据跳跃值生成组合(类似于我们在范围或循环中使用它的方式)。
每个组合中的元素数量基于 parent_list 的长度。如果父列表包含 10 个元素,我们需要输出中的每个列表都包含 10 个元素。
parent_list=['a','b','c', 'd']
jump=15
预期输出样本是
[[15,25,25,35],[30,50,10,10],[20,15,20,45]]
我使用了question中给出的解决方案,但它没有提供添加跳转参数的选项。分数也是允许的。
此程序找出所有 n
个正整数的组合,其总和为 total
,并且其中至少有一个是 jump
的倍数。它以递归方式工作,如果当前序列已经包含原始 jump
.
倍数的元素,则将 jump
设置为 1
def find_sum(n, total, jump, seq=()):
if n == 0:
if total == 0 and jump == 1: yield seq
return
for i in range(1, total+1):
yield from find_sum(n - 1, total - i, jump if i % jump else 1, seq + (i,))
for seq in find_sum(4, 100, 15):
print(seq)
还有很多解决方案。
我希望生成一个组合列表,使总数始终为 100。必须根据跳跃值生成组合(类似于我们在范围或循环中使用它的方式)。 每个组合中的元素数量基于 parent_list 的长度。如果父列表包含 10 个元素,我们需要输出中的每个列表都包含 10 个元素。
parent_list=['a','b','c', 'd']
jump=15
预期输出样本是
[[15,25,25,35],[30,50,10,10],[20,15,20,45]]
我使用了question中给出的解决方案,但它没有提供添加跳转参数的选项。分数也是允许的。
此程序找出所有 n
个正整数的组合,其总和为 total
,并且其中至少有一个是 jump
的倍数。它以递归方式工作,如果当前序列已经包含原始 jump
.
jump
设置为 1
def find_sum(n, total, jump, seq=()):
if n == 0:
if total == 0 and jump == 1: yield seq
return
for i in range(1, total+1):
yield from find_sum(n - 1, total - i, jump if i % jump else 1, seq + (i,))
for seq in find_sum(4, 100, 15):
print(seq)
还有很多解决方案。