返回枚举索引

时间:2019-07-10 00:06:24

标签: python

我基本上是想返回DNA字符串的起始索引,其中A和G在接下来的五个字母中占多数。

查看代码

def a_g_majority_positions(dna):

    ### BEGIN SOLUTION
    list=[]
    for index, item in enumerate(dna):
            count=0
            x=0
            index1=index
            while count < 5:
                letter=dna[index1]
                index1+=1
                count+=1
                if letter == 'A':
                    x+=1
                elif letter == 'G':
                    x+=1
            if x>=3:
                list.append(index)
    return list




    ### END SOLUTION
a_g_majority_positions("AACCGGTTAACCGGTT")

我总是得到超出范围错误的字符串索引。末尾dna的正确答案是[0,1,4,5,8,9]

3 个答案:

答案 0 :(得分:1)

使用count方法计算感兴趣的字母。从五个开始,直到您没有足够的位置为止:

def a_g_majority_positions(dna):

    lst = []
    for start5 in range(len(dna)-4):
        five = dna[start5:start5+5]
        if five.count('A') + five.count('G') >= 3:
            lst.append(start5)
    return lst

或者,对于单语句版本,检查每个字符是否在“ AG”中:

lst = [start5 for start5 in range(len(dna)-4)
       if sum(char in "AG"
              for char in dna[start5:start5+5]) >= 3]

两种情况下的输出均为

[0, 1, 4, 5, 8, 9]

答案 1 :(得分:0)

当剩下的字母少于5个时,您需要跳出for循环:

def a_g_majority_positions(dna):
    result = list()
    for index, item in enumerate(dna):
        if index + 5 >= len(dna):
            break
        count = 0
        x = 0
        while count < 5:
            letter = dna[index + count]
            count += 1
            if letter == 'A':
                x += 1
            elif letter == 'G':
                x += 1
        if x >= 3:
            result.append(index)
    return result

print(a_g_majority_positions("AACCGGTTAACCGGTT"))

输出

[0, 1, 4, 5, 8, 9]

注意

请勿使用list作为变量名。它是内置类,您将其用作变量名将很难引入错误。

答案 2 :(得分:0)

当索引大于len(dna) - 5时,您需要尽早中断该功能。否则,您将尝试访问超出范围的dna[len(dna)]

def a_g_majority_positions(dna):

### BEGIN SOLUTION
list=[]
for index, item in enumerate(dna):
        count=0
        x=0
        index1=index
        if index > len(dna) - 5:
            break
        while count < 5:
            letter=dna[index1]
            index1+=1
            count+=1
            if letter == 'A':
                x+=1
            elif letter == 'G':
                x+=1
        if x>=3:
            list.append(index)
return list




### END SOLUTION
a_g_majority_positions("AACCGGTTAACCGGTT")

# Result [0, 1, 4, 5, 8, 9]