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?
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.
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
( , !)
, :
itertools.combinations():
itertools.combinations()
r .. , , ., , . , , .
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)] >>>
Source: https://habr.com/ru/post/1716680/More articles:Deploying .NET SQLite and Click-Once - .netneeding random "hot or not" algorithm / solutions - c #How can I in C # stream.Read into an unmanaged memory stream? - performanceThe fastest way to escape a string in JavaME - javaHow to check if a Win32 window pointer is a valid .Net Control? - c #https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1716681/steps-to-publish-software-to-be-purchased-via-registration&usg=ALkJrhj8CE6Xr-4NKIXU8VA7614ZXTsA-gHow to install the debugger visualizer? - debuggingAre visual effects of runtime Expression Blend possible? - visibilityWhere do the Label_ markers appear in Reflector and how to decipher them? - c #How to show custom 404 page in ASP.NET without redirecting? - c #All Articles