Skip to content
Related Articles

Related Articles

Improve Article

Print all subsequences of a string in Python

  • Difficulty Level : Medium
  • Last Updated : 20 Aug, 2020

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.

Input : abc
Output : a, b, c, ab, bc, ac, abc

Input : aaa
Output : a, aa, aaa


Using Pick and Don’t Pick concept :


def printSubSequences(STR, subSTR=""):
        To print all subsequences of string
            Pick and Don’t Pick
            STR = string
            subSTR = to store subsequence
    if len(STR) == 0:
        print(subSTR, end=" ")
    # we add adding 1st character in string
    printSubSequences(STR[:-1], subSTR + STR[-1])
    Not adding first character of the string
    because the concept of subsequence either
    character will present or not
    printSubSequences(STR[:-1], subSTR)
def main():
    main function to drive code
    STR = "abc"
if __name__ == "__main__":
# by itsvinayak


cba cb ca c ba b a  

pythonic implementations:

Prerequisite: itertools.combinations() module in Python to print all possible combinations 


# Python Implementation of the approach
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 =' ')
# Testing with driver code
if __name__ == '__main__':
a b c ab ac bc abc


 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :