Python program to get all subsets of a given size of a set


In this article, we will learn about the solution to the problem statement given below.

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 itertools.combinations() method

Example

 Live Demo

# itertools module
import itertools
def findsubsets(s, n):
   return list(itertools.combinations(s, n))
#main
s = {1,2,3,4,5}
n = 4
print(findsubsets(s, n))

Output

[(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)]

Using map() and combination() method

Example

# itertools module
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))

Output

[{1, 2, 3, 4}, {1, 2, 3, 5}, {1, 2, 4, 5}, {1, 3, 4, 5}, {2, 3, 4, 5}]

Using comprehension in the list iterable

Example

 Live Demo

# itertools
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))

Output

[{1, 2, 3, 4}, {1, 2, 3, 5}, {1, 2, 4, 5}, {1, 3, 4, 5}, {2, 3, 4, 5}]

Conclusion

In this article, we have learned about how we can get all subsets of a given size of a set

Updated on: 24-Dec-2019

493 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements