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

2024-10-01 09:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在不使用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

我知道这不会有任何作用,它只会添加第一个组合,而不会添加其他任何内容。在


Tags: 函数in元素示例列表fordef情况
2条回答

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

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

在您的示例中,不使用外部导入或递归调用:

^{pr2}$

我对@Hooked的回答有异议。。。在

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

我的第一个问题是争论

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

返回以下错误

^{pr2}$

我是这样修好的

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

相关问题 更多 >