HomePythonPython Program to Create a Class and Get All Possible Distinct Subsets from a Set

Python Program to Create a Class and Get All Possible Distinct Subsets from a Set

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()

How it works

  1. The program defines a class SubsetGenerator with an initializer that takes the original set as input and initializes an empty list subsets to store the generated subsets.
  2. The generate_subsets method initializes the recursive process to generate subsets and returns the list of subsets.
  3. The _generate_subsets_recursive method is a helper function that generates subsets recursively. It starts by adding a copy of the current subset to the subsets list.
  4. It then iterates through the remaining elements of the original set, recursively adding and removing elements to generate subsets.
  5. The main function takes user input for the set elements, creates an instance of SubsetGenerator, and generates subsets.
  6. The program finally prints all the generated subsets.

Input / Output

Python Program to Create a Class and Get All Possible Distinct Subsets from a Set

Leave A Reply

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

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...