简体   繁体   中英

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]])

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.

  1. You assume the first element as a required member of every combination.
  2. You append only the last value of li from your for loop; lifeat should get them all.

For the second problem, change your return statement to two lines:

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM