문제

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?

도움이 되었습니까?

해결책 2

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

다른 팁

You can also do this using regular expressions, something like the following:

[m.start()+1 for m in re.finditer("(?=ATAT)", "GATATATGCATATACTT")])

Functional style pwned all :D

def mysub2(string, sub):    
    return [x+1 for x in range(len(string)) if string[x:x+len(sub)] == sub]




>>> def mysub(string, sub):          
    return [x+1 for x in range(len(string)) if string[x:x+len(sub)] == sub]

>>> st = "GATATATGCATATACTT"
>>> sub2 = "ATAT"
>>> mysub(st, sub2)
[2, 4, 10]
>>> 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top