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



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

Given a set, write a Python program to generate all possible subset of size n of given set within a list.
Examples:

 

Input : {1, 2, 3}, n = 2
Output : [{1, 2}, {1, 3}, {2, 3}]

Input : {1, 2, 3, 4}, n = 3
Output : [{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}]

We have already discussed the same problem using the Naive approach in this article. This article focuses on the Pythonic approaches to Print all subsets of a given size of a set.

 

 

Python has itertools.combinations(iterable, n) which Return n length subsequences of elements from the input iterable. This can be used to Print all subsets of a given size of a set. Now, we have various alternatives to use this function.

Code #1 : 
Simply pass the set as iterable and the size as arguments in the itertools.combinations() to directly fetch the combination list.

# Python Program to Print
# all subsets of given size of a set
import itertools
def findsubsets(s, n):
    return list(itertools.combinations(s, n))
# Driver Code
s = {1, 2, 3}
n = 2
print(findsubsets(s, n))

Output:

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

 

Code #2 : 
We can also use an alternative to the above-discussed method which is mapping set to itertools.combinations() function.

# Python Program to Print
# all subsets of given size of a set
import itertools
from itertools import combinations, chain
def findsubsets(s, n):
    return list(map(set, itertools.combinations(s, n)))
    
# Driver Code
s = {1, 2, 3}
n = 2
print(findsubsets(s, n))

Output:

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

 

Code #3 : 
Another method is to use for loop in itertools.combinations() function and append the combination sets to the list.

# Python Program to Print
# all subsets of given size of a set
import itertools
# def findsubsets(s, n):
def findsubsets(s, n):
    return [set(i) for i in itertools.combinations(s, n)]
    
# Driver Code
s = {1, 2, 3, 4}
n = 3
print(findsubsets(s, n))

Output:

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

Code #4:

Many a time when this question is asked in interviews, it’s better to answer without using any module. So, here is the solution that does not use itertools module:

def subsets(numbers):
    if numbers == []:
        return [[]]
    x = subsets(numbers[1:])
    return x + [[numbers[0]] + y for y in x]
# wrapper function
def subsets_of_given_size(numbers, n):
    return [x for x in subsets(numbers) if len(x)==n]
if __name__ == '__main__':
    numbers = [1, 2, 3, 4]
    n = 3
    print(subsets_of_given_size(numbers, n))

Output:

[[2, 3, 4], [1, 3, 4], [1, 2, 4], [1, 2, 3]]

Last Updated on March 1, 2022 by admin

Leave a Reply

Your email address will not be published. Required fields are marked *

Recommended Blogs