我正在尝试编写一个程序,该程序可以在DNA序列的定义长度的元素之间移动,我无法理解我从循环中获得的输出。在循环的前四个迭代中似乎移帧很好,然后似乎恢复为旧序列。我已经非常努力地理解这种行为,但是我对于编程来说还是太陌生了,无法解决这个问题,对此非常感谢。
这是我的代码:
seq = "ACTGCATTTTGCATTTT"
search = "TGCATTTTG"
import regex as re
def kmers(text,n):
for a in text:
b = text[text.index(a):text.index(a)+n]
c = len(re.findall(b, text, overlapped=True))
print ("the count for " + b + " is " + str(c))
(kmers(seq,3))
和我的输出:
the count for ACT is 1
the count for CTG is 1
the count for TGC is 2
the count for GCA is 2
#I expected 'CAT' next, from here on I don't understand the behaviour
the count for CTG is 1
the count for ACT is 1
the count for TGC is 2
the count for TGC is 2
the count for TGC is 2
the count for TGC is 2
the count for GCA is 2
the count for CTG is 1
the count for ACT is 1
the count for TGC is 2
the count for TGC is 2
the count for TGC is 2
the count for TGC is 2
显然,最终我希望删除重复项,等等,但是由于我的for循环为什么不起作用,我希望它阻止了我的前进,以使其变得更好。
谢谢
text.index
总是返回找到的第一个索引。由于您seq
逐个字母地循环访问字母,因此第一次遇到先前找到的字母时,您会得到怪异的结果。
第5个字母是第一个重复字母a c
,因此text.index('c')
返回的第一个字母c
,1而不是您期望的4的索引-并且您在上一次命中时复制了字母c
。
这种方法效率低下-您似乎对遍历索引比对字母更感兴趣,因此我将使用:
for a in range(len(text)-(n-1)):
b = text[a:a+n]
c = len(re.findall(b, text, overlapped=True))
print ("the count for " + b + " is " + str(c))
与其每次都搜索索引,这都是低效率的,并且在您的情况下会产生错误的结果。findall
这也是一种低效率的计数方法-具体来说,defaultdict
可以构建字典来提高计数效率。
请注意,您已经可以使用不错的内置插件:
>>> from collections import Counter
>>> seq='ACTGCATTTTGCATTTT'
>>> Counter((seq[i:i+3] for i in range(len(seq)-2)))
Counter({'TTT': 4, 'TGC': 2, 'GCA': 2, 'CAT': 2, 'ATT': 2, 'ACT': 1, 'CTG': 1, 'TTG': 1})
最终匹配是字符串结尾的位置,您可以忽略它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句