【问题标题】:is it good to pass output list as parameter in recursive permutations code在递归排列代码中将输出列表作为参数传递是否很好
【发布时间】:2019-06-04 00:25:08
【问题描述】:

我有一个排列代码,我必须返回包含所有排列列表的输出列表。例如,如果我有 [0,1] 作为输入,我需要返回 [[0,1],[1,0]] 作为输出。为此,我将输出数组作为递归调用中的参数传递。这是一个好主意还是更好地在 permute 中创建一个嵌套函数 permute_list 始终可以访问输出列表?只是想知道一个好的python用户应该做什么。

import copy

def permute(l):
    """
    Return a list of permutations

    Examples:
       permute([0, 1]) returns [ [0, 1], [1, 0] ]

    Args:
      l(list): list of items to be permuted

    Returns:
      list of permutation with each permuted item being represented by a list
    """
    output = []
    if len(l) == 0:
        return [[]]
    else:
        permute_list(l,0,output)
    return output
def permute_list(l,ind,output):

    if ind == len(l) - 1:
        a = l.copy()
        output.append(a)
        print(f"{output}")

    for i in range(ind,len(l)):
        l[ind],l[i] = l[i],l[ind]
        permute_list(l,ind + 1,output)
        l[i],l[ind] = l[ind],l[i]

【问题讨论】:

标签: python


【解决方案1】:

我没有检查您的代码的准确性,但为了回答您的问题,output 的处理方式似乎没有问题。 output 是一个列表,并且在 python 中变量名称用作对对象的引用,将其作为参数传递应该不会影响您的堆栈长度。

【讨论】:

    猜你喜欢
    • 2014-11-02
    • 1970-01-01
    • 2017-07-16
    • 2013-11-13
    • 2015-04-17
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多