Print all subsequences of a string in Python
Last Updated :
20 Feb, 2023
Given a string, we have to find out all subsequences of it. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order.
Examples:
Input : abc
Output : a, b, c, ab, bc, ac, abc
Input : aaa
Output : a, aa, aaa
Using Pick and Don’t Pick concept :
Python3
def printSubSequences( STR , subSTR = ""):
if len ( STR ) = = 0 :
print (subSTR, end = " " )
return
printSubSequences( STR [: - 1 ], subSTR + STR [ - 1 ])
printSubSequences( STR [: - 1 ], subSTR)
return
def main():
STR = "abc"
printSubSequences( STR )
if __name__ = = "__main__" :
main()
|
Output:
cba cb ca c ba b a
Time Complexity:
The time complexity of this algorithm is O(2^n) because we are making 2 recursive calls for each character of the string, i.e. one with the character included in the subsequence and the other one without the character.
Space Complexity:
The space complexity of this algorithm is O(n) because we are using recursive calls to print the subsequences, which will be stored on the stack.
pythonic implementations:
Prerequisite: itertools.combinations() module in Python to print all possible combinations
Python3
import itertools
def Sub_Sequences( STR ):
combs = []
for l in range ( 1 , len ( STR ) + 1 ):
combs.append( list (itertools.combinations( STR , l)))
for c in combs:
for t in c:
print (' '.join(t), end =' ')
if __name__ = = '__main__' :
Sub_Sequences( 'abc' )
|
Output:
a b c ab ac bc abc
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...