coursera多倫多python learning week 4
阿新 • • 發佈:2019-02-10
字元長度
def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
字元長度比較返回邏輯值
def is_longer(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna1 is longer than DNA sequence dna2. >>> is_longer('ATCG', 'AT') True >>> is_longer('ATCG', 'ATCGGA') False """ if len(dna1) > len(dna2): return True else: return False
相同字元個數
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 """ return dna.count(nucleotide)
字元相同返回邏輯值
def contains_sequence(dna1, dna2): """ (str, str) -> bool Return True if and only if DNA sequence dna2 occurs in the DNA sequence dna1. >>> contains_sequence('ATCGGC', 'GG') True >>> contains_sequence('ATCGGC', 'GT') False """ if dna2 in dna1: return True else: return False
判斷是否包含某字元
def is_valid_sequence(nucleotide):
""" (str) -> bool
Return True if and only if the DNA sequence is valid.
>>> is_valid_sequence('A')
True
>>> is_valid_sequence('T')
True
>>>is_valid_sequence('C')
True
>>>is_valid_sequence('G')
True
>>>is_valid_sequence('D')
False
>>>is_valid_sequence('B')
False
"""
str='ATCG'
if str.find(nucleotide)==-1:
return False
else:
return True
插入字元
def insert_sequence(dna1,dna2,location):
""" (str, str, int) -> str
return the dna sequence obtained bu inserting dna2 into dna1 at the location.
>>>insert_sequence('CCGG','AT',2)
'CCATGG'
>>>insert_sequence('AT','G',1)
'AGT'
"""
return dna1[:location] + dna2 + dna1[location:]
輸出對映字元
def get_complement(nucleotide):
""" (str) -> str
return the nucleotide's complement
>>>get_complement('A')
'T'
>>>get_complement('C')
'G'
"""
in_str= 'ATCG'
out_str= 'TAGC'
map_table=str.maketrans(in_str,out_str)
return nucleotide.translate(map_table)
字元逆序排列
def get_complementary_sequence(dna):
""" (str) -> str
return the complementary dna sequence
>>>get_complementary_sequence('AT')
'TA'
>>>get_complementary_sequence('CG')
'GC'
"""
return dna[::-1]