![](/img/trans.png)
[英]fastest way in python to enumerate all combinations and return the index
[英]Return index with enumerate
我基本上是想返回一个 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]
使用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]
当剩下的字母少于 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
作为变量名。 它是内置类,您将通过将其用作变量名来引入难以发现的错误。
当 index 大于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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.