【问题标题】:Can't append items to a global list from recursive function although I'm using global for list, how to do that in py?尽管我使用全局列表,但无法将项目从递归函数附加到全局列表,如何在 py 中做到这一点?
【发布时间】:2021-01-12 10:14:59
【问题描述】:

我正在使用递归函数来查找所有列表的子集并制作它们的二维列表。这是我编码的方式:

我将一个列表和一个索引传递给我的函数,然后我选择是否保留该索引的项目。所以我用新列表中下一个项目的索引再调用该函数两次(一次不进行更改,一次删除项目)。每当我传递的索引与列表的长度相等时,我就达到了我想要制作的最终列表。

问题是最终列表没有附加到主列表!不知道能不能追加或者算法有问题或者...

这是它的样子:

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

输出是:

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

【问题讨论】:

  • 提示:一个函数可以修改它的参数,如果它是可变的。

标签: python algorithm recursion scope


【解决方案1】:

我会采取不同的方向,并建议您不要使用 global 来存储递归函数的结果,而是通过递归本身:

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

输出

% python3 test.py
[['a', 'b', 'c'], ['a', 'c'], ['a', 'b'], ['b', 'c'], ['c'], ['b'], ['a']]
% 

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    相关资源
    最近更新 更多