pythonstringbioinformaticsrosalind

Rosalind resolution noob


This is my solution to the problem presented here: http://rosalind.info/problems/subs/.

def subs(string,subString):
    lista=[]
    i=0
    while i < (len(string)-len(subString)):
        if string[i:(i+len(subString)-1)]==subString:
           lista.append(i)
        i+=1
    return lista

What is wrong with my code?


Solution

  • One thing that's wrong with it is that you can't add an integer to a list, you need to append it:

    lista.append(i)
    

    Then the slice is too short: in Python, a[i:j] gives you all characters from position i up to but not including position j. Because you subtract 1 from the length, it will compare one character too few every time.

    Finally, to get the exact answer asked for in the question, you need to add 1 to the position because Python indexes arrays starting from 0, not 1.

    def subs(string,subString):
        lista = []
        i = 0
        while i < (len(string)-len(subString)):
            if string[i:i+len(subString)] == subString:
               lista.append(i + 1)
            i += 1
        return lista