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?
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)])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.