我正在 python 中寻找一种算法,该算法将返回数字列表的所有可能组合,允许重复元素并加起来达到某个数字...
例如,给定目标数字 7,以及列表[2, 3, 4]
我希望能够生成以下组合:
2, 2, 3
2, 3, 2
3, 2, 2
3, 4
4, 3
我了解如何获取列表的所有可能组合,但我不知道如何以这种方式包含重复项。任何帮助,将不胜感激!
您可以创建递归函数并应用必要的逻辑:
def combinations(d, current=[], sum_to = 7):
if sum(current) == 7:
yield current
else:
for i in d:
if sum(current+[i]) <= 7:
yield from combinations(d, current+[i])
print(list(combinations([2, 3, 4])))
Output:
[[2, 2, 3], [2, 3, 2], [3, 2, 2], [3, 4], [4, 3]]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)