【发布时间】: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