[英]Output of recursive python function
I have a problem with a function which should return all possible combinations in a list, without repeating the sample. 我的函数有问题,该函数应在列表中返回所有可能的组合,而无需重复示例。
The function works perfectly but I'm unable to get a list of all the combinations: 该功能运行完美,但我无法获得所有组合的列表:
abc = ['a','b','c','d','e']
def combi(pre, listg, stage=1,first = 1):
if len(listg)==0:
return []
start = first
lifeat =[]
for i in range(start,len(listg)):
lifeat.append(pre + [listg[i]])
print('stage: ',stage,'|| ',i,' ',pre + [listg[i]])
diff = set(listg[i:]) - set(pre+[listg[i]])
seted= [item for item in listg[i:] if item in diff]
li = combi(pre+ [listg[i]],seted,stage+1, first= 0)
#print('li : ',li)
return lifeat+li
def all_combi(liste):
return combi([liste[0]], liste)
all_combi(abc)
the printed result : print('stage: ',stage,'|| ',i,' ',pre + [listg[i]])
打印结果: print('stage: ',stage,'|| ',i,' ',pre + [listg[i]])
stage: 1 || 1 ['a', 'b']
stage: 2 || 0 ['a', 'b', 'c']
stage: 3 || 0 ['a', 'b', 'c', 'd']
stage: 4 || 0 ['a', 'b', 'c', 'd', 'e']
stage: 3 || 1 ['a', 'b', 'c', 'e']
stage: 2 || 1 ['a', 'b', 'd']
stage: 3 || 0 ['a', 'b', 'd', 'e']
stage: 2 || 2 ['a', 'b', 'e']
stage: 1 || 2 ['a', 'c']
stage: 2 || 0 ['a', 'c', 'd']
stage: 3 || 0 ['a', 'c', 'd', 'e']
stage: 2 || 1 ['a', 'c', 'e']
stage: 1 || 3 ['a', 'd']
stage: 2 || 0 ['a', 'd', 'e']
stage: 1 || 4 ['a', 'e']
This is the output I got : output 这是我得到的输出: 输出
[['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e']]
thank you in advance for any help. 预先感谢您的任何帮助。
You have several problems in your logic. 您的逻辑中有几个问题。 I strongly recommend that you use incremental programming to sort out your difficulties. 我强烈建议您使用增量编程来解决您的困难。
li
from your for
loop; 您只能在for
循环中附加li
的最后一个值; lifeat
should get them all. lifeat
应该让他们全部。 For the second problem, change your return statement to two lines: 对于第二个问题,将return语句更改为两行:
lifeat += li
return lifeat
This improves your result to 这可以改善您的结果
[['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd', 'e'],
['a', 'b', 'c', 'e'], ['a', 'b', 'd'], ['a', 'b', 'd', 'e'], ['a', 'b', 'e'],
['a', 'c'], ['a', 'c', 'd'], ['a', 'c', 'd', 'e'], ['a', 'c', 'e'], ['a', 'd'],
['a', 'd', 'e'], ['a', 'e']]
I'll leave the initialisation problem to you. 我将初始化问题留给您。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.