如何在不使用itertools模块或递归编程的情况下在Python上创建置换?

如何在不使用itertools模块或递归编程的情况下在Python上创建置换?,python,permutation,Python,Permutation,我需要创建一个函数,而不使用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:

我需要创建一个函数,而不使用
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
def置换(concento,k):
a、 b=列表(),列表()
对于我来说:
如果len(b)

我知道这没有任何作用,它只会添加第一个组合,其他什么都没有。

正如@John在评论中提到的,代码是:

这适用于不使用外部导入或递归调用的示例:

for x in permutations([1,2,3],2):
    print (x)

(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)

我对@Hooked的答案有异议

首先,对于py来说,我是一个完全的新手,但我一直在寻找类似上面代码的东西。我现在在

我的第一个问题是争论

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文档页面上看到。签出。当然,对于python,它使用itertools,但是对于低级语言,它提供了可以轻松移植到python的算法。
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
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