【问题标题】:I can't make permutations using a recursive function in Python我无法在 Python 中使用递归函数进行排列
【发布时间】:2021-06-20 11:02:54
【问题描述】:

我正在尝试创建一个递归函数来打印给定集合的所有可能排列。

perm = []  # list to make permutations
S = {1,2,3,4}  # set of elements which have not used for the permutation yet

def make_perm():
  if not S:
    print(perm)
  else:
    for x in S:
      perm.append(x)
      S.remove(x)
      make_perm()
      perm.pop()
      S.add(x)
      
make_perm()

但是,这个程序不起作用:它只输出[1,2,3,4]。 是什么原因?

(添加)我希望程序输出如下。

> [1,2,3,4]
> [1,2,4,3]
> [1,3,2,4]
> [1,3,4,2]
      ︙

当它符合 PyPy3(7.3.0) 时,它只输出[1,2,3,4]。 但是当它符合Python3(3.8.2)时,它的输出如下。

> [1,2,3,4]
> [1,2,4,3]
> [1,3,2,4]
> [1,3,2,4]
> [1,3,4,2]
      ︙

一些输出重复。我很困惑这些输出不正确且不同:(。

【问题讨论】:

  • 那么你期望得到什么?
  • 请注意,任何集合顺序的概念都是任意的——包括迭代和插入顺序。无法保证在迭代时删除/添加到集合具有明确定义甚至稳定的行为;通过扩展,任何使用它的算法都有实现定义的行为。

标签: python


【解决方案1】:

问题是您在迭代 S 时对其进行了修改。你应该遍历一个副本

for x in S.copy():
    perm.append(x)
    S.remove(x)
    make_perm()
    perm.pop()
    S.add(x)

输出

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

注意set不保证顺序,你应该改用list

S = [1, 2, 3, 4]

for x in S[:]:
    perm.append(x)
    S.remove(x)
    make_perm()
    perm.pop()
    S.append(x)

【讨论】:

    【解决方案2】:

    每当您执行perm.append(x) 时,您从S 追加一个项目而不是排列,因此在4 次之后,S 为空并且您获得[1, 2, 3, 4]

    请参阅here 如何生成列表的所有排列(在集合的情况下非常相似)。

    【讨论】:

    • 但是原始函数确实有效——它打印所有排列。例如之后获得[1, 2, 3, 4],将其打印出来并将数字添加回集合中。
    • 我不太了解这是如何回答问题的。 “经过 4 次,S 为空,您获得 [1, 2, 3, 4]”是重点——[1, 2, 3, 4] 是一种排列。然后函数继续下一个排列。
    【解决方案3】:

    没有回答这个问题,但我看到您使用的代码不符合有关此类功能应如何工作的标准。 目前,您的函数需要在 外部 设置 2 个字段。 你不希望这样 - 函数应该只依赖于它们的参数。 此外,您应该 return 它们而不是打印所有排列。这使您可以稍后使用排列。

    def make_perm(iterable):
      if not iterable: return null
      else:
        permutations = []
        for elem in iterable:
          #push to permutations
        return permutations
          
    s = {1, 2, 3, 4}
    permutations = make_perm(s)
    print(permutations)
    

    如果您不想重新发明轮子并且可以使用模块,请查看itertools.permutations

    【讨论】:

      猜你喜欢
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 2023-04-06
      • 2019-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多