
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Get All Subsets of a Given Size of a Set in Python
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