繁体   English   中英

计算DNA序列字符串中的核苷酸

[英]Counting nucleotides in DNA sequence string

我已经编写了此函数,但该函数无法正常运行。 有什么想法吗? 我知道问题在于char定义...

def count_nucleotides(dna, nucleotide):
    ''' (str, str) -> int

    Return the number of occurrences of nucleotide in the DNA sequence dna.

    >>> count_nucleotides('ATCGGC', 'G')
    2
    >>> count_nucleotides('ATCTA', 'G')
    0
    '''

    num_nucleodites=0

    for char in dna:
        if char is ('A'or'T'or'C'or'G'):
            num_nucleodites=num_nucleodites + 1      
    return num_nucleodites

那怎么办

def count_nucleotides(dna, nucleotide):
    return dna.count(nucleotide)

(请注意,就家庭作业而言,这可能不会奏效……)

根据您的评论之一,您似乎正在寻找一个以上核苷酸的重叠序列。 可以使用正则表达式来完成:

import re
def find_overlapping(needle, haystack):
    return len(re.findall("(?=" + needle + ")", haystack))

然后可以像这样使用它:

>>> find_overlapping("AGA", "AGAGAGAAGAGAG")
5

您编写的or条件与您的思维方式不符。应检查每个char ,然后使用or分隔它们,如下所示:-

if char is 'A' or char is 'T' ... so on:

但是,您可以使用in运算符使用更好的方法。

尝试这个: -

for char in dna:
        if char in 'ATCG':
            num_nucleodites=num_nucleodites + 1 

但是,由于您在question说过只想计算一个特定的元素,因此您无需检查所有4个字符。.这就是使用基本的for循环代码的样子:-

def count_nucleotides(dna, nucleotide):
    num_nucleotide = 0
    for char in dna:
        if char == nucleotide:
            num_nucleotide = num_nucletode + 1
    return num_nucleotide

要不就: -

def count_nucleotides(dna, nucleotide):
    return dna.count(nucleotide)
if char is ('A'or'T'or'C'or'G'):

那就是评估'A' or 'T'并返回'A',然后检查char是否等于它-在Python REPL中尝试:

>>> ('A'or'T'or'C'or'G')
'A'

我认为您的意思是:

if char in ('A', 'T', 'C', 'G'):
string = "ATAGTTCATGTACCGTTGCAGGGGG"
print [(i,string.count(i)) for i in list("ACTG")]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM