如何在Python中创建排列,不使用itertools模块或递归编程?
我需要创建一个函数,不使用itertools
,这个函数可以生成一个包含给定元素的元组的排列列表。
举个例子:
perm({1,2,3}, 2)
应该返回 [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
。
这是我写的代码:
def permutacion(conjunto, k):
a, b = list(), list()
for i in conjunto:
if len(b) < k and i not in b:
b.append(i)
b = tuple(b)
a.append(b)
return a
我知道这段代码没有实现什么,它只会添加第一个组合,其他的都不会有。
2 个回答
1
我对@Hooked的回答有点问题...
首先,我对Python完全是个新手,但我在找类似上面那段代码的东西。我现在正在Repl.it上输入这段代码。
我遇到的第一个问题是参数
for x in permutations([1,2,3],2):
print x
这导致了以下错误
line 26
print x
^
SyntaxError: Missing parentheses in call to 'print'
我这样修复了它
for x in permutations([1,2,3],2):
print (x)
但现在又出现了这个错误:
line 25, in <module>
for x in permutations([1,2,3],2):
File "main.py", line 14, in permutations
cycles[i] -= 1
TypeError: 'range' object does not support item assignment
到目前为止,我完全不知道该去哪里调试代码。不过,我看到很多人提到过itertools,说它的文档里有相关代码。我复制了那个,结果可以运行。这是代码:
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = list(range(n, n-r, -1))
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
3
正如@John在评论中提到的,itertools.permutations
的代码是:
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = list(range(n, n-r, -1))
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
这个代码可以在你的例子中使用,不需要引入其他库或者使用递归调用:
for x in permutations([1,2,3],2):
print (x)
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)