0

私は、私が望むように機能しないこの関数を書きました。アイデアはありますか?問題はどういうわけか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
4

5 に答える 5

3

ただどうですか

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

(宿題に関しては、おそらく飛ぶことはないでしょう...)

于 2012-10-20T04:46:47.007 に答える
2

あなたのコメントの 1 つによると、複数のヌクレオチドの重複配列を探しているようです。これは正規表現で行うことができます:

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

その後、次のように使用できます。

>>> find_overlapping("AGA", "AGAGAGAAGAGAG")
5
于 2012-10-20T05:04:23.327 に答える
0

あなたが書いた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)
于 2012-10-20T04:43:56.140 に答える
0
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'):
于 2012-10-20T04:54:33.470 に答える
0
string = "ATAGTTCATGTACCGTTGCAGGGGG"
print [(i,string.count(i)) for i in list("ACTG")]
于 2014-09-26T17:43:12.240 に答える