In this Python program, we will create a class called SubsetGenerator
to find all possible distinct subsets of a given set. Subsets are the combinations of elements from the original set, and we will implement a method to generate these subsets.
Problem statement
Given a set, we need to create a class that can generate all distinct subsets of the set, including the empty set and the set itself.
Python Program to Create a Class and Get All Possible Distinct Subsets from a Set
class SubsetGenerator: def __init__(self, original_set): self.original_set = original_set self.subsets = [] def generate_subsets(self): self._generate_subsets_recursive([], 0) return self.subsets def _generate_subsets_recursive(self, current_subset, start_index): self.subsets.append(current_subset[:]) # Add a copy of the current subset for i in range(start_index, len(self.original_set)): current_subset.append(self.original_set[i]) self._generate_subsets_recursive(current_subset, i + 1) current_subset.pop() def main(): input_set = input("Enter elements of the set separated by spaces: ").split() subset_generator = SubsetGenerator(input_set) subsets = subset_generator.generate_subsets() print("\nAll possible distinct subsets:") for subset in subsets: print(subset) if __name__ == "__main__": main()
Python
​x
28
1
class SubsetGenerator:
2
def __init__(self, original_set):
3
self.original_set = original_set
4
self.subsets = []
5
​
6
def generate_subsets(self):
7
self._generate_subsets_recursive([], 0)
8
return self.subsets
9
​
10
def _generate_subsets_recursive(self, current_subset, start_index):
11
self.subsets.append(current_subset[:]) # Add a copy of the current subset
12
13
for i in range(start_index, len(self.original_set)):
14
current_subset.append(self.original_set[i])
15
self._generate_subsets_recursive(current_subset, i + 1)
16
current_subset.pop()
17
​
18
def main():
19
input_set = input("Enter elements of the set separated by spaces: ").split()
20
subset_generator = SubsetGenerator(input_set)
21
subsets = subset_generator.generate_subsets()
22
​
23
print("\nAll possible distinct subsets:")
24
for subset in subsets:
25
print(subset)
26
​
27
if __name__ == "__main__":
28
main()
How it works
- The program defines a class
SubsetGenerator
with an initializer that takes the original set as input and initializes an empty listsubsets
to store the generated subsets. - The
generate_subsets
method initializes the recursive process to generate subsets and returns the list of subsets. - The
_generate_subsets_recursive
method is a helper function that generates subsets recursively. It starts by adding a copy of the current subset to thesubsets
list. - It then iterates through the remaining elements of the original set, recursively adding and removing elements to generate subsets.
- The
main
function takes user input for the set elements, creates an instance ofSubsetGenerator
, and generates subsets. - The program finally prints all the generated subsets.
Input / Output
