Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to get all subsets of a given size of a set
In this article, we will learn how to generate all subsets of a specific size from a given set. This is a common problem in combinatorics where we need to find all possible combinations of n elements from a larger set.
Problem statement ? We are given a set, we need to list all the subsets of size n.
We have three approaches to solve the problem using Python's itertools module ?
Using itertools.combinations() Method
The most straightforward approach uses itertools.combinations() which returns tuples of the specified size ?
import itertools
def findsubsets(s, n):
return list(itertools.combinations(s, n))
# Driver Code
s = {1, 2, 3, 4, 5}
n = 4
print(findsubsets(s, n))
[(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)]
Using map() with combinations() Method
This approach uses map() to convert each tuple combination back to a set format ?
import itertools
from itertools import combinations
def findsubsets(s, n):
return list(map(set, itertools.combinations(s, n)))
# Driver Code
s = {1, 2, 3, 4, 5}
n = 4
print(findsubsets(s, n))
[{1, 2, 3, 4}, {1, 2, 3, 5}, {1, 2, 4, 5}, {1, 3, 4, 5}, {2, 3, 4, 5}]
Using List Comprehension
This method uses list comprehension to convert combinations into sets, providing a more Pythonic approach ?
import itertools
def findsubsets(s, n):
return [set(i) for i in itertools.combinations(s, n)]
# Driver Code
s = {1, 2, 3, 4, 5}
n = 4
print(findsubsets(s, n))
[{1, 2, 3, 4}, {1, 2, 3, 5}, {1, 2, 4, 5}, {1, 3, 4, 5}, {2, 3, 4, 5}]
Comparison
| Method | Output Format | Best For |
|---|---|---|
combinations() |
Tuples | When order matters |
map() + combinations() |
Sets | Functional programming style |
| List comprehension | Sets | Readable, Pythonic code |
Conclusion
All three methods efficiently generate subsets of a given size using itertools.combinations(). Choose tuples for ordered results or sets when order doesn't matter. List comprehension offers the most readable solution.
