[英]Return index with enumerate
I am basically trying to return the starting index of a DNA string where A and G form the majority over the next five letters.我基本上是想返回一个 DNA 字符串的起始索引,其中 A 和 G 在接下来的五个字母中占多数。
See code查看代码
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")
I always get a string index out of range error.我总是得到一个字符串索引超出范围错误。 The correct answer for the dna at the end is [0,1,4,5,8,9]
最后dna的正确答案是[0,1,4,5,8,9]
Use the count
method to count the letters of interest.使用
count
方法计算感兴趣的字母。 Start the run of five up until you don't have enough positions left:开始五个人的运行,直到您没有足够的位置:
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
Or, for the one-statement version, checking each character for being in "AG":或者,对于单语句版本,检查每个字符是否在“AG”中:
lst = [start5 for start5 in range(len(dna)-4)
if sum(char in "AG"
for char in dna[start5:start5+5]) >= 3]
Output in either case is两种情况下的输出都是
[0, 1, 4, 5, 8, 9]
You need to break out of the for
loop when there are less than 5 letters left:当剩下的字母少于 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"))
Output输出
[0, 1, 4, 5, 8, 9]
Note笔记
Don't use list
as a variable name.不要使用
list
作为变量名。 It's built-in class and you will introduce hard to find errors by using it as a variable name.它是内置类,您将通过将其用作变量名来引入难以发现的错误。
You need to break early from the function when index is greater than len(dna) - 5
.当 index 大于
len(dna) - 5
时,您需要提前中断函数。 Otherwise you try to access dna[len(dna)]
, which is out of range.否则,您尝试访问超出范围的
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.