我试图使用递归从集合{1,2,3,4,5}生成所有可能的3种组合。
预期产出:[1,2,3,1,2,4,1,2,5,2,3,4,2,3,5,3,4,5,1,3,4,1,3,5,1,4,5,2,4,5]
我所使用的逻辑是,任何三集组合都会有第一个元素,或者没有。我还使用了列表的连接。示例:
[1,2,3] + [a,b]给出[1,2,3,a,b]
下面使用上述逻辑的代码似乎不起作用。我是自学的,所以如果我犯了错误,请对我有耐心.我知道我的递归中有错误。但是,试图在递归问题中回溯输出对我来说是相当困难的。请让我知道这个程序的缺陷在哪里,并引导我找到合适的资源,这样的问题才能得到更好的处理。在这样的问题上,正确的思维方式是什么?非常感谢你的帮助。
代码:
sol = [1,2,3,4,5]
b=3
y= []
def combinations(sol, b):
global y
if len(sol) == b or len(sol)==1 :
return [sol]
y.append([[sol[0]] + combinations(sol[1:], b-1)] + combinations(sol[1:],b))
return y
print(combinations(sol,b)发布于 2021-12-01 06:31:13
你可以这样做,让你的功能成为一个生成器。在每个步骤中,循环遍历可能的起始单元,然后循环递归中的下一步返回的结果。
sol = [1,2,3,4,5]
b=3
def combinations(sol, b):
if b == 0:
yield []
else:
for i in range(len(sol)-b+1):
for j in combinations(sol[i+1:],b-1):
yield [sol[i]]+j
print(list(combinations(sol,b)))输出:
[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]发布于 2021-12-01 06:19:18
使用itertools中提供的机器
from itertools import combinations
list(combinations(v, 3))输出
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]https://stackoverflow.com/questions/70179839
复制相似问题