2017-10-17 84 views
-1

所以我想知道是否有人想帮助我。我甚至不知道从哪里开始?任何帮助,将不胜感激。count_bases返回字典

编写一个函数count_bases来计算每个字母在给定字符串中出现的次数。结果应以字典形式返回,其中大写字母作为键和出现次数作为(整数)值。

例如,当使用字符串'ATGATAGG'调用函数时,应该返回{'A': 3, 'T': 2, 'G': 3, 'C': 0}。请确保你的函数使用return,而不是print()。字典中键的顺序不需要遵循这个顺序(2个标记)。

确保您的函数在序列字符串中传递任何较低和/或大写的DNA字符时有效。 (2分)

DNA序列有时含有除A,C,G到T以外的字母以指示简并核苷酸。例如,R可以代表A或G(嘌呤碱基)。如果程序遇到除A,C,G或T之外的任何字母,它还应计算该字母的频率并在字典对象内返回。 (2分)。

回答

0

使用下面的代码:

def count_bases(input_str): 
    result = {} 
    for s in input_str: 
     try: 
      result[s]+=1 
     except: 
      result[s] = 1 

    return result 

print(count_bases('ATGATAGG')) 

输出:

{'A': 3, 'T': 2, 'G': 3} 
0

试试:

def f(input): 
    d = {} 
    for s in input: 
    d[s] = d.get(s,0)+1 
    return d 
0
from collections import Counter 

def count_bases(sequence): 
    # since you want to count both lower and upper case letters, 
    # it'd be better if you convert the input sequence to either upper or lower. 
    sequence = sequence.upper() 
    # Counter (from collections) does the counting for you. It takes list as input. 
    # So, list(sequence) will separate letters from your sequence into a list of letters ('abc' => ['a', 'b', 'c']) 
    # It returns you a Counter object. Since you want a dictionary, cast it to dict. 
    return dict(Counter(list(sequence))) 

count_bases( 'ATGATAGGaatdga')

{ 'A':6, 'T':3, 'G':4, 'd':1}

+1

不太可能是有意义的人谁也 “不知道如何开始” 。 OP必须知道'Counter'是'collections'包中的一个类。 –