【问题标题】:How to generate increasing permutations of a list in Python without itertools.combinations如何在没有 itertools.combinations 的情况下在 Python 中生成列表的递增排列
【发布时间】:2019-03-06 09:56:12
【问题描述】:

如何在没有 itertools.combinations 的情况下在 Python 中生成列表的递增排列:

我正在尝试创建一个函数,该函数将生成列表的所有排列,但仅限于 len(n) 集,并且只能从左到右增加。例如,如果我有列表 l = [2,4,5,7,9] 和 n=4,结果应该包括 [2,4,5,7], [2,4,7,9], [ 2,5,7,9] 但不是 [9,7,4,2], [9,4,7,2]。这是我到目前为止所做的:

def permutation(lst):

    if len(lst) == 0:
        return []

    if len(lst) == 1:
        return [lst]

    l = []

    for i in range(0, len(lst)):
       m = lst[i]

       new = lst[:i] + lst[i+1:]

       for p in permutation(new):
           l.append([m] + p)
    return l

测试:

data = list([1,2,3,4,5,6])
for p in permutation(data):
    print p

【问题讨论】:

  • 这是为了上课,还是你可以use itertools.combinations?即使您不能使用 itertools.combinations 本身,它的文档也包含两个不同的 Python 实现,可以达到相同的效果。
  • 不要删除你的代码;表现出努力是好的问题与“为我做作业”问题的区别。

标签: python algorithm combinations permutation


【解决方案1】:

您所描述的正是 itertools.combinations 所做的:

from itertools import combinations
l = [2,4,5,7,9]
n = 4
for c in combinations(l, n):
    print(list(c))

这个输出:

[2, 4, 5, 7]
[2, 4, 5, 9]
[2, 4, 7, 9]
[2, 5, 7, 9]
[4, 5, 7, 9]

但如果不想实际使用itertools.combinations,可以参考documentation中的Python如何实现:

def combinations(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

【讨论】:

  • 我遇到过这个实现,但我想知道如何将它修改为 len(n),例如,n=4。此外,我不清楚如何调用这个函数。
  • @J.Dawson:对于您的示例,combinations([2,4,5,7,9], 4)。它创建了一个迭代器,而不是list(因为如果你急切地创建它们,组合结果会变得很大,通常只需一个接一个地迭代它们并在之后将它们丢弃),但你可以将它包装在list()构造函数来使迭代器生成一个list。在您的示例用例中,您不需要 list,因此 for comb in combinations([2, 4, 5, 7, 9], 4): print(list(comb)) 完全符合您的要求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多