0

I am currently following along ayoutube tutorial for pset 6 DNA, and have a small question regarding a specific function. In this function, it basically takes a substring and a string, and counts the number of times the substring appears in the string and returns it. I have attached the code in the tutorial, and another version that I hav tried but does not give the same output

Tutorial code:

def getmaxlength(s, sub):
    answer = [0] * len(s)
    for i in range(len(s) - len(sub), -1, -1):
        if s[i: i + len(sub) ] == sub:
            if i + len(sub) > len(s) - 1:
                answer[i] = 1
            else:
                answer[i] = 1 + answer[i + len(sub)]
    return max(answer)

From what i understand, it creates a list of 0s with the same length, and starting from the back, compares the substring with the string and changes the list to the specific count (so far), after which it returns the max value in the string which would be the number of times the substring appears.

Below is the code I have tried writing but doesnt give the same output

def getmaxlength(s, sub):
    value = 0
    for i in range(len(s) - len(sub), -1, -1):
        if s[i: i + len(sub) ] == sub:
            value +=1
    return value

Would appreciate some insight as to why the output is different. Thank you all!

You must log in to answer this question.

Browse other questions tagged .