给出一个这样的列表:
num = [1, 2, 3, 4, 5]有10种三要素组合:
[123, 124, 125, 134, 135, 145, 234, 235, 245, 345]如何生成此列表?
发布于 2009-09-02 13:04:30
使用itertools.combinations
import itertools
num = [1, 2, 3, 4, 5]
combinations = []
for combination in itertools.combinations(num, 3):
combinations.append(int("".join(str(i) for i in combination)))
# => [123, 124, 125, 134, 135, 145, 234, 235, 245, 345]
print len(combinations)
# => 10编辑
如果您只对组合的数量感兴趣,则可以跳过int()、join()和str()。itertools.combinations()为您提供了足够好的元组。
发布于 2009-09-02 13:07:27
你说的是combinations。有n!/(k!* (n - k)!)从n个元素列表中获取k个元素的方法。所以:
>>> num = [1, 2, 3, 4, 5]
>>> fac = lambda n: 1 if n < 2 else n * fac(n - 1)
>>> combos = lambda n, k: fac(n) / fac(k) / fac(n - k)
>>> combos(len(num), 3)
10仅当您实际想要生成所有组合时才使用itertools.combinations。如果你只是想知道不同组合的数量,就不会。
此外,与使用上面显示的代码相比,有更有效的方法来计算组合的数量。例如,
>>> from operator import truediv, mul
>>> from itertools import starmap
>>> from functools import reduce
>>> combos = lambda n, k: reduce(mul, starmap(truediv, zip(range(n, n - k, -1), range(k, 0, -1))))
>>> combos(len(num), 3)
10.0(请注意,此代码使用了浮点除法!)
发布于 2009-09-02 13:06:10
我相信你要找的是binomial coefficient
https://stackoverflow.com/questions/1367550
复制相似问题