Description:
To get all possible subsets from a given set of integers, we can implement the built-in combination function in the itertools library.
The method: combinations(iterable, r) returns successive r-length combinations of elements in the iterable.
Therefore if a set contains 3 integers, we can have subsets of length 0, 1, 2 and 3.
Python Code:
import itertools
class Subsets:
def __init__(self, integers):
self.integers = integers
def get_subsets(self):
subsets = []
for i in range(len(self.integers)+1):
for element in list(itertools.combinations(self.integers, i)):
subsets.append(element)
return subsets
def main():
integers = set(map(int, input("Enter a set of distinct integers: ").split(' ')))
obj = Subsets(integers)
possible_subsets = obj.get_subsets()
for subset in possible_subsets:
print(subset)
if __name__ == "__main__":
main()
Output:
Enter a set of distinct integers: 1 2 3
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)
Comments