Write a program to Create a Class and Get All Possible Subsets from a Set of Distinct Integers in Python
In this tutorial we are going to learn about creating a Class and Get All Possible Subsets from a Set of Distinct Integers in Python.
Python Program to Create a Class and Get All Possible Subsets from a Set of Distinct Integers
class sub: def f1(self, s1): return self.f2(, sorted(s1)) def f2(self, curr, s1): if s1: return self.f2(curr, s1[1:]) + self.f2(curr + [s1], s1[1:]) return [curr] a= n=int(input("Enter number of elements of list: ")) for i in range(0,n): b=int(input("Enter element: ")) a.append(b) print("Subsets: ") print(sub().f1(a))
- A class called sub is created and two methods f1 and f2 are defined.
- In main, the number of elements is taken from the user.
- Using a for loop, the elements are taken from the user and appended to an empty list.
- Then, the method f1 of the class sub is called by passing the list taken from the user as the parameter.
- Method f1 in turn calls method f2 with an empty list and the sorted list taken from the user as parameters.
- Method f2 is a recursive function.
- This method computes all the possible subsets by splitting the current list part by part starting from an empty list and updating the value of the current list.
- This continues till the list becomes empty.
- The current value of the list which is a list containing subsets as separate lists is returned.
- The final result is printed.