0

My exercise consists in counting a subsequence in a binary string, but I can't use the count method because, for example, if I have the subsequence '00' in the string '10010000', the count method will return '3' but the correct answer is '4'.

I tried this:

def subseq_uguale(stringa,testo,lunghezza):
    f=0
    for i in range(len(testo)-lunghezza+1):
        confronta=''
        for j in range(lunghezza):
            confronta+=testo[i+j]
        if confronta==stringa:
            f+=1
    return f

Where 'lunghezza' is the length of the subsequence, 'testo' is the sequence and 'stringa' is the subsequence. But it takes too much time! How can I solve this?

  • 2
    Does this answers your question: https://stackoverflow.com/questions/2970520/string-count-with-overlapping-occurrences? – Dani Mesejo Nov 11 '21 at 09:19

1 Answers1

1

Try this

def subseq_uguale(stringa, testo):
    f=0
    for i in range(len(testo)+1-len(stringa)):
        if stringa==testo[i:i+len(stringa)]:
            f+=1
    return f
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 11 '21 at 10:39