Skip to content

Instantly share code, notes, and snippets.

@adolli
Last active September 30, 2019 09:37
Show Gist options
  • Save adolli/768fd9c33e8d1905ccb45e460459b06d to your computer and use it in GitHub Desktop.
Save adolli/768fd9c33e8d1905ccb45e460459b06d to your computer and use it in GitHub Desktop.
permutation/combination

permutation与combination

没事随手瞎写的,性能明显不是最好的,而且也没有完全使用生成器

# coding=utf-8

import itertools 


def combinations(l, n):
    if len(l) < n:
        raise StopIteration
    if n == 0:
        yield ()
    else:
        a0 = l[0]
        ax = l[1:]
        for r in combinations(ax, n - 1):
            yield (a0, ) + r
        for r in combinations(ax, n):
            yield r


def permutations(l, n):
    if len(l) < n:
        raise StopIteration
    if n == 0:
        yield ()
    else:
        for i, x in enumerate(l):
            ax = l[:i] + l[i + 1:]
            for r in permutations(ax, n - 1):
                yield (x, ) + r


for p in combinations([1, 2, 3], 1):
    print(p)

for p in permutations([1, 2, 3], 3):
    print(p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment