如何使用用户定义的递归函数(Python)一次获取列表的所有排列
How to get all permutations of a list taken k things at at a time using a user defined recursive function(Python)
我想制作一个递归算法,生成一次取 k 个整数的列表的所有排列。
具体来说,我想做的是从头开始创建一个递归函数Perm(list, k)
,返回满足以下条件的输出。
from itertools import permutations
li = [1,2,3,4]
set(permutations(li, 2)) == set(Perm(li, 2))
我参考了 link 中 Shailaja 的代码 (Perm(lst,n)
) 进行了尝试:Recursive Algorithm to generate all permutations of length k of a list in Python
由于函数 returns 是一个嵌套列表,我尝试将嵌套列表转换为一组元组。但是,我无法找到任何解决方案,因为该函数是一个递归算法。谁能帮我更改 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)}
Since the function returns a nested list, I've tried to convert the nested list to a set of tuples.
是的,这确实是需要的。所以 Perm
应该产生元组。
这是 Perm
的可能递归实现:
def Perm(lst, size):
if size <= 0:
yield () # empty tuple
else:
for i, val in enumerate(lst):
for p in Perm(lst[:i] + lst[i+1:], size-1):
yield (val, *p)
这通过了问题中给出的测试。
我想制作一个递归算法,生成一次取 k 个整数的列表的所有排列。
具体来说,我想做的是从头开始创建一个递归函数Perm(list, k)
,返回满足以下条件的输出。
from itertools import permutations
li = [1,2,3,4]
set(permutations(li, 2)) == set(Perm(li, 2))
我参考了 link 中 Shailaja 的代码 (Perm(lst,n)
) 进行了尝试:Recursive Algorithm to generate all permutations of length k of a list in Python
由于函数 returns 是一个嵌套列表,我尝试将嵌套列表转换为一组元组。但是,我无法找到任何解决方案,因为该函数是一个递归算法。谁能帮我更改 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)}
Since the function returns a nested list, I've tried to convert the nested list to a set of tuples.
是的,这确实是需要的。所以 Perm
应该产生元组。
这是 Perm
的可能递归实现:
def Perm(lst, size):
if size <= 0:
yield () # empty tuple
else:
for i, val in enumerate(lst):
for p in Perm(lst[:i] + lst[i+1:], size-1):
yield (val, *p)
这通过了问题中给出的测试。