计算一系列母题的分数

2024-05-13 22:45:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经实现了一个函数。对于图片中的每一列,它取最常用的元素并从该列中的元素总数中减去该元素。然后把这些数字加起来。 This image shows what the function does.

有没有办法让它更快? 这是我的代码:

def scoreMotifs(motifs):
'''This function computes the score of list of motifs'''
z = []
for i in range(len(motifs[0])):
    y = ''
    for j in range(len(motifs)):
        y += motifs[j][i]
    z.append(y)
print z
totalscore = 0
for string in z:
    score = len(string)-max([string.count('A'),string.count('C'), string.count('G'), string.count('T')])
    totalscore += score
return totalscore  

motifs = ['GCG','AAG','AAG','ACG','CAA']
scoreMotifs(motifs)
['GAAAC', 'CAACA', 'GGGGA']
5

Tags: ofthein元素forstringlencount
1条回答
网友
1楼 · 发布于 2024-05-13 22:45:05

好的,所以我用line_profiler来分析你的代码:

from random import randrange

@profile
def scoreMotifs(motifs):
    '''This function computes the score of list of motifs'''
    z = []
    for i in range(len(motifs[0])):
        y = ''
        for j in range(len(motifs)):
            y += motifs[j][i]
        z.append(y)
    totalscore = 0
    for string in z:
        score = len(string)-max([string.count('A'),string.count('C'), string.count('G'), string.count('T')])
        totalscore += score
    return totalscore   

def random_seq():
    dna_mapping = ['T', 'A', 'C', 'G']
    return ''.join([dna_mapping[randrange(4)] for _ in range(3)])

motifs = [random_seq() for _ in range(1000000)]
print scoreMotifs(motifs)

结果如下:

^{pr2}$

有大量的计算:

y += motifs[j][i]

不过,还有一种更好的方法来转置字符串,使用zip技巧。因此,您可以将代码重写为:

from random import randrange

@profile
def scoreMotifs(motifs):
    '''This function computes the score of list of motifs'''
    z = zip(*motifs)
    totalscore = 0
    for string in z:
        score = len(string)-max([string.count('A'),string.count('C'), string.count('G'), string.count('T')])
        totalscore += score
    return totalscore  

def random_seq():
    dna_mapping = ['T', 'A', 'C', 'G']
    return ''.join([dna_mapping[randrange(4)] for _ in range(3)])


motifs = [random_seq() for _ in range(1000000)]
print scoreMotifs(motifs)

motifs = ['GCG','AAG','AAG','ACG','CAA']
print scoreMotifs(motifs)

总时间:

Total time: 0.61699 s

我认为这是一个相当不错的进步。在

相关问题 更多 >