I need to generate all the combinations with length k
from a list of length n
, and I must do it using recursion.
For Example:
INPUT: choose_sets([1,2,3,4],3)
OUTPUT: [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
INPUT: choose_sets([1,2,3,4],2)
OUTPUT: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
I'm stuck implementing this in code, so I would be happy for some help. This is my code so far (I'm missing something just don't know what):
def choose_sets(lst,k):
if k == len(lst):
return lst
if k == 0:
return []
if k > len(lst):
return []
sets=[]
sub_lst=lst[:]
sub_lst.remove(sub_lst[0])
a= choose_sets(sub_lst,k-1)
for i in a:
i.append(lst[0])
sets.append(a)
b= choose_sets(sub_lst,k)
sets.append(b)
return sets