Python Program to Create a Class and Get All Possible Subsets from a Set of Distinct Integers
In this example, we will write a python program to create a class and get all possible subsets from a set of distinct integers. To better understand this example, make sure you have knowledge of the following tutorials:-
Python Program to Convert temperatures using Classes
class Subset:
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[0]], 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(Subset().f1(a))The output of the above program is:-
Enter number of elements of list: 3
Enter element: 4
Enter element: 3
Enter element: 7
Subsets:
[[], [7], [4], [4, 7], [3], [3, 7], [3, 4], [3, 4, 7]]
Enter element: 4
Enter element: 3
Enter element: 7
Subsets:
[[], [7], [4], [4, 7], [3], [3, 7], [3, 4], [3, 4, 7]]
Program Explanation
- A class named “Subset” is defined that has two methods f1 and f2.
- The number of elements is taken from the user and using a for loop, the elements of the list are taken.
- The f1 method of the class is called passing the list as a parameter.
- The f2 method is a recursive function that generates all the sublist until the list becomes empty.
- The final result is printed.
