没事随手瞎写的,性能明显不是最好的,而且也没有完全使用生成器
# 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)