finding all possible subsequences in a given string

Question:

I have written this piece of code and it prints all substrings of a given string but I want it to print all the possible subsequences.

from itertools import combinations_with_replacement
s = 'MISSISSIPPI'
lst = []
for i,j in combinations_with_replacement(range(len(s)), 2):
        print(s[i:(j+1)])

Asked By: challenger

||

Answers:

One simple way to do so is to verify if the list you are making already has the case that you are iterating over. If you have already seen it, then skip it, if not, then append it to your list of seen combinations.

from itertools import combinations_with_replacement

s = 'MISSISSIPPI'
lst = []

for i,j in combinations_with_replacement(range(len(s)), 2):
    if s[i:(j+1)] not in lst:
        lst.append(s[i:(j+1)]) # save new combination into list
        print(lst[-1]) # print new combination

To be sure that all cases are covered, it really helps to make a drawing of combination that the loop will go over. Suppose a generic string, where letters are represented by their position in the python list, for example 0 to 3.

Here are the numbers generated by “combinations_with_replacement”

00, 01, 02, 03,
11, 12, 13,
22, 23,
33

Answered By: marcmorin99

Use combinations to get subsequences. That’s what combinations is for.

from itertools import combinations

def all_subsequences(s):
    out = set()
    for r in range(1, len(s) + 1):
        for c in combinations(s, r):
            out.add(''.join(c))
    return sorted(out)

Example:

>>> all_subsequences('HELLO')
['E', 'EL', 'ELL', 'ELLO', 'ELO', 'EO', 'H', 'HE', 'HEL', 'HELL', 'HELLO', 'HELO',
 'HEO', 'HL', 'HLL', 'HLLO', 'HLO', 'HO', 'L', 'LL', 'LLO', 'LO', 'O']
>>> all_subsequences('WORLD')
['D', 'L', 'LD', 'O', 'OD', 'OL', 'OLD', 'OR', 'ORD', 'ORL', 'ORLD', 'R', 'RD',
 'RL', 'RLD', 'W', 'WD', 'WL', 'WLD', 'WO', 'WOD', 'WOL', 'WOLD', 'WOR', 'WORD',
 'WORL', 'WORLD', 'WR', 'WRD', 'WRL', 'WRLD']
Answered By: kaya3

Simple Video Explanation of Backtracking based solution – https://youtu.be/eHWD7TpZ_vE

Code in Java based on Backtracking

class FindAllSubsequencesSolution {

public static Set<String> findSubSeq(String s) {
    int n = s.length();
    //This variable will represent a candidate solution. Every element of this will be either 0 or 1.
    //Every position of this array corresponds to the character in the string at the same position.
    //Value 0 represents we are not including that character in the candidate solution. Value 1
    //represents we are including that character in the candidate solution.
    int[] candidateSolution = new int[n];
    //This variable represents the stage at which we have to make choice. The first stage at which we
    //have to make choice is first index of the string.
    int choiceStage = 0;

    //This variable will hold the final results.
    Set<String> resultSet = new HashSet<String>();


    findSubSeqUtil(s, candidateSolution, choiceStage, resultSet);
    return resultSet;
}

private static void findSubSeqUtil(String s, int[] candidateSolution, int choiceStage, Set<String> resultSet) {
    //If all choice stages have been covered and we have made one or the other choice at every stage.
    if(choiceStage == s.length()) {
        //CandidateSolution holds values 0/1 in all of its positions. Use that to convert to the relevant string
        //It is our subsequence.
        String ans = convertToString(candidateSolution, s);
        if(!ans.isBlank()) {
            resultSet.add(ans);
        }
        return;
    }

    //Exercising choice when we choose not to include the character at this position
    candidateSolution[choiceStage] = 0;
    findSubSeqUtil(s, candidateSolution, choiceStage+1, resultSet);

    //Exercising choice when we choose to include the character at this position
    candidateSolution[choiceStage] = 1;
    findSubSeqUtil(s, candidateSolution, choiceStage+1, resultSet);
}

private static String convertToString(int[] candidateSolution, String s) {
    int i;
    String ans = "";
    for(i=0; i<s.length(); i++) {
        if(candidateSolution[i] == 1) {
            ans = ans + s.charAt(i);
        }
    }
    return ans;
}

}

Answered By: user1677428
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.