Python Program To Find all the Subsets of a String

In Python, a subset of a string is a sequence of characters that is part of the original string. We can find all the subsets of a string using itertools module in Python. In this article, we will see how we can generate all the subsets of a string by making all possible combinations of characters in the string.

Syntax

itertools.combination(string,r)


The combination() function of itertools module takes the string and r which represents the size of different combinations of strings that are possible.It returns all the combinations of characters of the string that are possible.

Algorithm

• Initialize an empty list called a combination

• Use a for loop to generate all possible combinations of characters in the string using itertools.combination function.

• Filter out the ones that are not subsets of the original string

• Return the subsets

Example

In the following example, we first import the itertools module to generate all possible combinations of characters in the string. The find_subsets() function takes a string as input and returns all possible subsets of the string. The find_subset() method first creates an empty list to store all the subsets. Then with the help of for loop and itertools. combination() function it generates all the possible subsets of the string and stores them in the combination list. After all the combinations are generated and stored in the combination list we need to filter out the strings which are not subsets of the original string and store such subsets in a list named subset. This subset is then returned by the function as all possible subsets of the string.

import itertools

def find_subsets(string):
# Get all possible combinations of characters in the string
combinations = []
for i in range(len(string) + 1):
combinations += itertools.combinations(string, i)
# Filter out the ones that are not subsets of the original string
subsets = []
for c in combinations:
subset = ''.join(c)
if subset != '':
subsets.append(subset)
return subsets

# Test the function
string = 'abc'
subsets = find_subsets(string)
print(subsets)


Output

['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']


Conclusion

In this article, we discussed how we can generate all possible subsets of the string using itertools module in Python. Once all the possible combinations of characters in the strings are generated we need to filter out the strings which are not subsets of the original string. As a result, we get all the possible subsets of the string.

Updated on: 17-Apr-2023

780 Views