【发布时间】:2021-10-08 19:35:32
【问题描述】:
我想做一个递归算法,生成一个整数列表的所有排列,一次取 k 个东西。
具体来说,我想做的是从头开始创建一个递归函数Perm(list, k),返回满足以下条件的输出。
from itertools import permutations
li = [1,2,3,4]
set(permutations(li, 2)) == set(Perm(li, 2))
我通过以下链接参考 Shailaja 的代码 (Perm(lst,n)) 进行了尝试:Recursive Algorithm to generate all permutations of length k of a list in Python
由于该函数返回一个嵌套列表,我尝试将嵌套列表转换为一组元组。但是,我找不到任何解决方案,因为该函数是递归算法。谁能帮我更改Perm 函数以获得以下输出格式?非常感谢。
# the output of set(Perm(li, 2))
{(1, 2),
(1, 3),
(1, 4),
(2, 1),
(2, 3),
(2, 4),
(3, 1),
(3, 2),
(3, 4),
(4, 1),
(4, 2),
(4, 3)}
【问题讨论】:
-
li可以包含重复项吗? -
[list(i) for i in permutations(li, 2)] == Perm(li, 2)? -
@CristiFati umm 这里我只想更改
Perm函数本身。 -
我没有更改任何其他内容。尝试打印相等测试成员,并注意集合是无序的。
-
@CristiFati 我明白你的意思,但在这里我被要求不要更改
set(permutations(li, 2)) == set(Perm(li, 2))等式。所以Perm函数的输出格式应该改一下。
标签: python list algorithm recursion permutation