【问题标题】:permutation of a list of numbers done recursively in python在python中递归完成的数字列表的排列
【发布时间】:2017-08-04 05:40:41
【问题描述】:

所以基本上我是在尝试获取一个数字列表并编写一个递归函数,该函数在列表列表中输出所有可能的输出。

我的代码:

def permutations(lst):
    if len(lst) <= 1:
        return lst
    l = []
    for i in range(len(lst)):
        m = lst[i]
        remlst = lst[:i] + lst[i+1:]
        for p in permutations(remlst):
            l.append([m] + p)
        return l

我收到一些关于无法附加 int 的错误。

简单的输出:

>>>permutations([1,2])
[[1,2],[2,1]]

【问题讨论】:

  • 给我们一个堆栈跟踪:)

标签: python-3.x recursion permutation


【解决方案1】:

在 itertools 中有一个实现:

import itertools
for p in itertools.permutations(list):
   # do stuff

此外,要修复您自己的功能,请注意在您的“基本情况”len(lst) &lt;= 1 您返回一个列表,而不是列表列表。另外,第二个 return 语句应该移出循环;

def permutations(lst):
    if len(lst) <= 1:
        return [lst]
    l = []
    for i in range(len(lst)):
        m = lst[i]
        remlst = lst[:i] + lst[i+1:]
        for p in permutations(remlst):
            l.append([m] + p)
    return l

【讨论】:

    【解决方案2】:

    因为你遍历了permutations的结果

    for p in permutations(remlst):
    

    您的基本案例需要像递归案例一样返回列表列表,否则您会收到错误 TypeError: can only concatenate list (not "int") to list

    你还需要在外部for循环之后返回。

    def permutations(lst):
        if len(lst) <= 1:
            return [lst] # [[X]]
        l = []
        for i in range(len(lst)):
            m = lst[i]
            remlst = lst[:i] + lst[i+1:]
            for p in permutations(remlst):
                l.append([m] + p)
        return l # return at end of outer for loop
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 2012-10-18
      • 2016-06-19
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      相关资源
      最近更新 更多