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

PythonServer Side ProgrammingProgramming

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

raja
Published on 24-Dec-2019 09:52:57
Advertisements