理解itertools组合源代码

时间:2019-06-01 20:10:43

标签: python algorithm combinations itertools combinatorics

根据官方Python文档here

itertools.combinations()函数的实现方式如下:

def combinations(iterable, r):
    '''
    combinations('ABCD', 2) --> AB AC AD BC BD CD
    combinations(range(4), 3) --> 012 013 023 123
    '''
    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)

我完全无法跟踪函数内部发生的情况。

有人可以为此提供一个简单的分步说明吗?

编辑

具体来说,我不理解代码的这一部分:

 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

0 个答案:

没有答案