【问题标题】:The code is printing none instead of different permutations代码打印无而不是不同的排列
【发布时间】:2020-12-25 12:52:59
【问题描述】:

这里的程序是用python编写的,它旨在打印输入的不同排列。 例如 输入:[1,2,3]

输出:[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]

代码

def swap(a,b):
    temp=a
    a=b
    b=temp
    return a,b
def permut(z,l,n):
    if l==n:
        return (z)
    else:
        for i in range(l,n):
            swap(z[l],z[i])
            permut(z,l+1,n)
            swap(z[l],z[i])
p=[1,2,3]
t=permut(p,0,3)
print(t)

我得到的是None,而不是得到理想的输出。

【问题讨论】:

  • 我认为你没有返回任何东西,所以变量 t 将得到 None 作为没有任何返回语句的函数返回 None
  • 由于参数是不可变的(在本例中为数字),您的 swap 函数将无法在原地交换 a、b 的值。

标签: python return permutation


【解决方案1】:

OP 代码错误

  • 由于参数是不可变的(在本例中为数字),swap 函数无法在原地交换 a、b 的值
  • 您没有汇总找到的排列

代码

def permut(a, k=0, results=None):
    # results array will store the permutations found
    if results is None:
        results = []
    if k == len(a):   # using len(a) means we don't need the argument n in OP code
      results.append(a[:])
    else:
      for i in range(k, len(a)):
         a[k], a[i] = a[i] ,a[k]  # swap values
         permut(a, k+1, results)
         a[k], a[i] = a[i], a[k]  # swap back
    return results

测试

p = [1,2,3]
t = permut(p)   # using default k = 0
print(t)

输出

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 2023-04-02
    • 2014-04-23
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多