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

时间:2011-04-20 13:56:48

标签: python python-3.x

我正试图找到一种编写组合函数的方法。我在哪里可以找到它?

4 个答案:

答案 0 :(得分:28)

实际的源代码是用C语言编写的,可以在文件itertoolsmodule.c中找到。

答案 1 :(得分:17)

请参阅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)

答案 2 :(得分:1)

可从以下网址下载最新资料来源:http://www.python.org/download/

尝试下载最新版本:Python 2.7.1

答案 3 :(得分:0)

while 循环解决方案可能相当混乱...我使用递归编写了一个“更容易理解”的代码。对于我们做出的每一个决定,我们都需要做出更多的决定,直到组合达到我们想要的长度(基本情况)。以下是 itertools.combinations 的代码,但考虑到排列只是组合的顺序敏感版本,您可以删除排序和哈希集并轻松使其成为 itertools.permuations 方法。

def combinations(curr, result, used):
    if len(curr) == l:
        result.add(tuple(sorted(curr))) #Modify this line to change it into itertools.permutations
        return
    else:
        for i in arr:
            if len(curr) == 0:
                check_set = set()
            else:
                check_set = used
            if i not in used:
                temp = curr + [i]
                check_set.add(i)
                combinations(temp, result, check_set)
            
相关问题