问题描述
我需要不使用itertools来编写递归迭代器置换(n),但是我不知道我需要在代码的递归部分中写什么。现在看起来像这样:
def permutations(n):
if n == 0:
yield []
else :
for i in permutations(n-1):
for i in permutations(2): print(i)
此行的输出应为[0,1],[1,0]。 我需要在代码中添加什么?
解决方法
这应该适合您的目的。
def permutations(n):
yield from permut((),tuple(range(n)))
def permut(left,right):
if not right:
yield left
for i,elem in enumerate(right):
yield from permut((*left,elem),(*right[:i],*right[i+1:]))