【Python小试】计算蛋白序列中指定氨基酸所占的比例

编码

from __future__ import division

def get_aa_percentage(protein, aa_list=['A','I','L','M','F','W','Y','V']):
    protein = protein.upper()
    protein_length = len(protein)
    total = 0
    for aa in aa_list:
        aa = aa.upper()
        aa_count = protein.count(aa)
        total += aa_count
    percentage = total * 100 / protein_length
    return percentage

assert get_aa_percentage("MSRSLLLRFLLFLLLLPPLP", ["M"]) == 5
assert get_aa_percentage("MSRSLLLRFLLFLLLLPPLP", ['M', 'L']) == 55
assert get_aa_percentage("MSRSLLLRFLLFLLLLPPLP", ['F', 'S', 'L']) == 70
assert get_aa_percentage("MSRSLLLRFLLFLLLLPPLP") == 65

解析

Python assert(断言)用于判断一个表达式,在表达式条件为 False 的时候触发异常。

断言可以在条件不满足程序运行的情况下直接返回错误,而不必等待程序运行后出现崩溃的情况。

assert expression

#等价于
if not expression:
    raise AssertionError

Ref:https://www.runoob.com/python3/python3-assert.html