Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

python - Can't append items to a global list from recursive function although I'm using global for list, how to do that in py?

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:

[[], [], [], []]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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']]
% 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...