[Getting started with algorithms and data structures] [Day2] Several methods for directly replacing elements in a list

There are 4 kinds of bases in DNA, namely ATCG, where the symbols "A" and "T" are complementary, and the symbols "C" and "G" are complementary, now given a DNA sequence, find his complement DNA sequence, write function DNA_strand (dna)

Branch structure

def DNA_strand(str):
    str_list = list(str)
    for i in range(len(str_list)):
        if str_list[i] =='A':
            str_list[i] = 'T'
        elif str_list[i] == 'T':
             str_list[i] = 'A'
        elif str_list[i] == 'C':
             str_list[i] = 'G'
        elif str_list[i] == 'G':
             str_list[i] = 'C'
    print(''.join(str_list))
DNA_strand("ATTGC")
DNA_strand("AAAAA")

Insert picture description here

dictionary

def DNA_strand(str):
    ref = {'A':'T','T':'A','C':'G','G':'C'}
    print(''.join(ref[i] for i in str))
DNA_strand("ATTGC")
DNA_strand("AAAAA")

Insert picture description here

function

def DNA_strand(str):
    table = ''.maketrans('ATGC','TACG')
    print(str.translate(table))
DNA_strand("ATTGC")
DNA_strand("AAAAA")

Insert picture description here

String replace method

def DNA_strand(dna):
    dna_dict = {'A':'T','T':'A','G':'C','C':'G'}
    dna_re = ''
    for i in dna:
        dna_re += i.replace(i,dna_dict[i])
    print(dna_re)
DNA_strand('ATTGC')
DNA_strand('AAAA')

For more exciting visit

Published 42 original articles · praised 28 · visits 4961

Guess you like

Origin blog.csdn.net/KaelCui/article/details/105307488