 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
# 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
# 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
Advertisements
 