【发布时间】:2019-06-04 00:25:08
【问题描述】:
我有一个排列代码,我必须返回包含所有排列列表的输出列表。例如,如果我有 [0,1] 作为输入,我需要返回 [[0,1],[1,0]] 作为输出。为此,我将输出数组作为递归调用中的参数传递。这是一个好主意还是更好地在 permute 中创建一个嵌套函数 permute_list 始终可以访问输出列表?只是想知道一个好的python用户应该做什么。
import copy
def permute(l):
"""
Return a list of permutations
Examples:
permute([0, 1]) returns [ [0, 1], [1, 0] ]
Args:
l(list): list of items to be permuted
Returns:
list of permutation with each permuted item being represented by a list
"""
output = []
if len(l) == 0:
return [[]]
else:
permute_list(l,0,output)
return output
def permute_list(l,ind,output):
if ind == len(l) - 1:
a = l.copy()
output.append(a)
print(f"{output}")
for i in range(ind,len(l)):
l[ind],l[i] = l[i],l[ind]
permute_list(l,ind + 1,output)
l[i],l[ind] = l[ind],l[i]
【问题讨论】:
-
您的解决方案有效吗?我会使用
itertools组合迭代器之一。
标签: python