Home > OS >  How to calculate combinations in Python
How to calculate combinations in Python

Time:02-01

I want to calculate a combination set as a collection of all possible subsets of k items selected from n items. For example, if n = 4 and k = 3, then the items are the integers (0, 1, 2, 3), then there are 4 possible combination elements:

[0, 1, 2]
[0, 1, 3]
[0, 2, 3]
[1, 2, 3]

Is there a function to do it in Python?

CodePudding user response:

itertools.combinations produces the desired output:

from itertools import combinations

n = 4
k = 3

# combinations() outputs tuples.
# Use list() to transform the tuples into lists.
print([list(combination) for combination in combinations(range(n), 3)])
  •  Tags:  
  • Related