我正在研究生物信息学的问题rosalind.org网站我遇到了一个问题,我编写的python脚本可以在较小的数据集上运行,但是当应用到更大的数据集时,我会得到IndexError: list index out of range
消息。在
基本上我有一个较小的基序和一个较大的DNA序列,我必须在DNA序列中找到这个基序的实例。当我把问题中的示例数据集放入脚本中时,它工作得很好,我得到了正确的答案。然而,使用更大的基序和序列会产生前面提到的错误。在
这是我的代码:
motif = "<motif around 9 characters>"
cMotif = list(motif)
motifLength = len(cMotif)
dna = "<DNA sequence around 900 characters>"
dnArray = list(dna)
locations = ""
position = 0
for nt in dnArray:
if (nt == cMotif[0]):
for x in range(0, (motifLength)):
if ((x + position) > len(dnArray)):
break
if (dnArray[position + x] == cMotif[x]):
if (x >= (motifLength - 1)):
locations += (str(position + 1) + " ")
break
else:
break
position += 1
print(locations)
第18行出现IndexError: list index out of range
错误,if (dnArray[position + x] == cMotif[x]):
因此我添加了
但没关系。在
干杯
为了方便起见,我建议您使用python的regex。在
它为
dna
中的motif
的每一次出现提供字符串中的开始索引和结束索引Python的列表是从零开始的,因此当}时,将是最后一个索引的1/1。您应该将测试更改为
(x + position) == len(dnArray)
尝试访问{if (x + position) >= len(dnArray):
以解决您的问题。在以下是引发错误的程序:
我将
if ((x + position) > len(dnArray)):
更改为if ((x + position) >= len(dnArray)):
,错误消失了,因为您的程序永远不会转到break
语句,因为您没有检查"="
条件。记住,在编程语言中,事情从0开始。在把这一行放在你的条件上方
^{pr2}$if ((x + position) > len(dnArray)):
,你就会知道原因了:此print语句的最后一行将指示
My position is: 33 and the length is: 33
请注意,您已经到达了行的末尾,并且它与break语句中的现有条件不匹配。在
相关问题 更多 >
编程相关推荐