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 calculator operations.

Below is a demonstration for the same −

Example

 Live Demo

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]
my_list = []
num_elem = int(input("Enter the number of elements in the list.. "))
for i in range(0,num_elem):
   elem=int(input("Enter the element.."))
   my_list.append(elem)
print("Subsets of the list are : ")
print(get_subset().sort_list(my_list))

Output

Enter the number of elements in the list.. 3
Enter the element..45
Enter the element..12
Enter the element..67
Subsets of the list are :
[[], [67], [45], [45, 67], [12], [12, 67], [12, 45], [12, 45, 67]]

Explanation

  • A class named ‘get_subset’ class is defined, that has functions like ‘sort_list’, and ‘subset_find’.
  • These are used to perform operations such as sort the list, and get all the possible subsets from the list data respectively.
  • An instance of this class is created.
  • The list data is entered, and operations are performed on it.
  • Relevant messages and output is displayed on the console.

Updated on: 12-Mar-2021

471 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements