如何在不使用 itertools 模块或递归编程的情况下在 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

我知道这不会做任何事情,它会添加第一个组合,没有别的。

正如@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)

我对@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

现在在这一点上,我不知道去哪里调试代码。 但是,我看到很多人指出迭代工具在其文档中包含代码。 我复制了它并且它有效。 这是代码:

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

相关内容

最新更新