我需要在不使用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
我知道这并没有做任何事情,它会添加第一个组合,而不是别的。
答案 0 :(得分:2)
正如@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 = range(n)
cycles = 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)
答案 1 :(得分:0)
我对@Hooked的答案有疑问...
首先,我是一个有关py的完全新手,但是我正在寻找类似上面的代码的东西。我目前正在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