在哪里可以找到itertools.combinations()函数的源代码

28 投票
4 回答
24663 浏览
提问于 2025-04-16 16:06

我想找个方法来写一个组合函数。请问我可以在哪里找到它呢?

4 个回答

1

接受的答案中的代码需要一些修改,但修改的请求已经满了。这里是来自itertools文档的一个更新版本,跟原来的代码大致相同,用Python写的:

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)
46

实际的源代码是用C语言写的,你可以在这个文件里找到:itertoolsmodule.c

31

可以查看一下 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 = 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)

撰写回答