gpt4 book ai didi

python - 查找列表元素的所有组合,包括重复元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:38:27 26 4
gpt4 key购买 nike

我正在 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])))

输出:

[[2, 2, 3], [2, 3, 2], [3, 2, 2], [3, 4], [4, 3]]

关于python - 查找列表元素的所有组合,包括重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com