How to calculate capabilities in python lists

Given a list like this:

num = [1, 2, 3, 4, 5]

There are 10 three-element combinations:

[123, 124, 125, 134, 135, 145, 234, 235, 245, 345]

How can I generate this list?

+3
source share
4 answers

Use 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

Edit

You can skip the int (), join (), and str () functions if you are only interested in the number of combinations. itertools.combinations () gives you tuples that can be good enough.

+10
source

You are talking about combinations . There are n! / (K! * (N - k)!) Ways to take k items from a list of n items. So:

>>> 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

( , !)

+5

, :

+2

itertools.combinations():

r .

. , , .

, , . , , .

>>> num = [1, 2, 3, 4, 5]
>>> [i for i in itertools.combinations(num,3)]
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5),
 (2, 4, 5), (3, 4, 5)]
>>> 
+2

Source: https://habr.com/ru/post/1716680/


All Articles