Hi,
i need to write a recursive function which gets a list and an integer k and returns a list of all the possibilities of creating sub lists to the length of k with the elements from the original list.
i hope i was clear enough..
here are some examples:
>>> choose_sets([1,2,3, 4],0)
[[]]
>>> choose_sets([1,2,3, 4],2)
[[2, 1], [3, 1], [4, 1], [3, 2], [4, 2], [3, 4]]
>>> choose_sets([1,2,3, 4],4)
[[1, 2, 3, 4]]
>>> choose_sets(,4)
[['d', 'c', 'b', 'a'], ['e', 'c', 'b', 'a'], ['d', 'e', 'b', 'a'], ['c', 'd', 'e', 'a'], ['b', 'c', 'd', 'e']]
i've already thought of an easy way to solve it :
def choose_sets_help(lst, k,ans):
''' Input: lst,
Output: a list of all k-length sub-lists '''
if len(lst)==k :
if lst not in ans:
ans.append(lst)
return ans
if len(lst)<k or k==0:
return [[]]
for elm in lst:
sub_lst=lst[:]
sub_lst.remove(elm)
choose_sets_help(sub_lst,k,ans)
return ans
def choose_sets(lst,k):
return choose_sets_help(lst,k,[])
and it works perfectly but then my teacher said i cant check for any repetitions in my code so the line :"if lst not in ans..." isn't allowed,
and now i cant think of a way to get the correct final list with no repetitioons in it
any ideas ?
thanks