combinations()函数(python)

itertools.combinations(iterable, r)

从可迭代对象iterable中选取r个单位进行组合,并返回一个生成元组的迭代器

定义

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)

举例:具体像这样

combinations()函数(python)_第1张图片

应用

枚举验证6174(python程序设计实验8)

你可能感兴趣的:(python学习)