Reputation: 3
I'm using a recursive function to find all of the lists' subsets and make a 2D list of them. This is the way I coded that:
I pass a list and an index to my function and I choose whether to keep the item of that index or not. So I call the function two more times (once with not making a change and once with deleting the item) with the index of the next item in the new list. Whenever the index I'm passing became equal with the length of the list I have reached the final list I wanted to make.
The problem is the final list doesn't append to the main list! I don't know whether I can do the appending or the algorithm has a problem or...
Here is how it looks like:
ans = [] # The main list which subsets will be added to
def zir_maj(li,idx=0):
global ans
if len(li) == idx: # if it be true I have reached the end of tree
ans.append(li)
return None # by this I will end the function
zir_maj(li, idx + 1) # I choose to keep my item
li.pop(idx)
zir_maj(li, idx) # I choose to delete my item
return ans # I return it for print
print(zir_maj(['a','b','c']))
and the output is:
[[], [], [], []]
Upvotes: 0
Views: 371
Reputation: 41905
I would take this in a different direction and suggest you not use a global
to store your recursive function's results, but rather bubble the results back up through the recursion itself:
def zir_maj(array):
permutations = []
if array:
head, *tail = array
sub_permutations = zir_maj(tail)
for sub_permutation in sub_permutations:
permutations.append([head, *sub_permutation])
permutations.extend(sub_permutations)
permutations.append([head])
return permutations
print(zir_maj(['a', 'b', 'c']))
OUTPUT
% python3 test.py
[['a', 'b', 'c'], ['a', 'c'], ['a', 'b'], ['b', 'c'], ['c'], ['b'], ['a']]
%
Upvotes: 1