Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Create a Class and Get All Possible Subsets from a Set of Distinct Integers
When it is required to create a class to get all the possible subsets of integers from a list, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to perform operations.
Below is a demonstration for the same −
Example
class get_subset:
def sort_list(self, my_list):
return self.subset_find([], sorted(my_list))
def subset_find(self, curr, my_list):
if my_list:
return self.subset_find(curr, my_list[1:]) + self.subset_find(curr + [my_list[0]], my_list[1:])
return [curr]
# Create a sample list for demonstration
my_list = [45, 12, 67]
print("Input list:", my_list)
print("Subsets of the list are:")
print(get_subset().sort_list(my_list))
The output of the above code is −
Input list: [45, 12, 67] Subsets of the list are: [[], [67], [45], [45, 67], [12], [12, 67], [12, 45], [12, 45, 67]]
How It Works
The algorithm uses recursive approach to generate subsets −
- For each element, we have two choices: include it or exclude it from the current subset
- The base case is when the list becomes empty, returning the current subset
- The recursion explores both paths: with and without the first element
Example with Different Input
class SubsetGenerator:
def get_all_subsets(self, nums):
return self._generate_subsets([], sorted(nums))
def _generate_subsets(self, current, remaining):
if not remaining:
return [current]
# Two choices: include or exclude the first element
without_first = self._generate_subsets(current, remaining[1:])
with_first = self._generate_subsets(current + [remaining[0]], remaining[1:])
return without_first + with_first
# Test with different inputs
generator = SubsetGenerator()
numbers = [1, 2, 3]
print("Input:", numbers)
print("All subsets:", generator.get_all_subsets(numbers))
print()
numbers = [5, 10]
print("Input:", numbers)
print("All subsets:", generator.get_all_subsets(numbers))
The output of the above code is −
Input: [1, 2, 3] All subsets: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] Input: [5, 10] All subsets: [[], [10], [5], [5, 10]]
Key Points
- The class uses recursion to generate all 2^n possible subsets
- Time complexity is O(2^n) where n is the number of elements
- Space complexity is O(n) for the recursion depth
- The input list is sorted to ensure consistent ordering
Conclusion
This class-based approach demonstrates how to generate all possible subsets using recursion. The algorithm explores both inclusion and exclusion of each element, producing all 2^n subsets for n distinct integers.
