python生信编程1-5

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunchengquan/article/details/85038894

Counting DNA Nucleotides/统计ATCG数

Problem

A string is simply an ordered collection of symbols selected from some alphabet and formed into a word; the length of a string is the number of symbols that it contains.

An example of a length 21 DNA string (whose alphabet contains the symbols ‘A’, ‘C’, ‘G’, and ‘T’) is “ATGCTTCAGAAAGGTCTTACG.”

Given: A DNA string of length at most 1000 nt.

Return: Four integers (separated by spaces) counting the respective number of times that the symbols ‘A’, ‘C’, ‘G’, and ‘T’ occur in .

Sample Dataset

AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC

Sample Output

20 12 17 21

#方法一 
symbols = 'ACGT'
sequence = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC' 

for i in symbols: 
    print(sequence.count(i), end = " ")

#方法二 
symbols = 'ACGT'
sequence = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC' 

counts = [sequence.count(i) for i in symbols]
print (' '.join(map(str, counts))) 
20 12 17 21

Transcribing DNA into RNA /DNA转录RNA

Problem

An RNA string is a string formed from the alphabet containing ‘A’, ‘C’, ‘G’, and ‘U’.

Given a DNA string
corresponding to a coding strand, its transcribed RNA string is formed by replacing all occurrences of ‘T’ in with ‘U’ in

.

Given: A DNA string

having length at most 1000 nt.

Return: The transcribed RNA string of

.

Sample Dataset

GATGGAACTTGACTACGTAAATT

Sample Output

GAUGGAACUUGACUACGUAAAUU

sequence = 'GATGGAACTTGACTACGTAAATT'
print(sequence.replace('T', 'U'))
GAUGGAACUUGACUACGUAAAUU

Complementing a Strand of DNA/DNA的反向互补链

Problem

In DNA strings, symbols ‘A’ and ‘T’ are complements of each other, as are ‘C’ and ‘G’.

The reverse complement of a DNA string
is the string formed by reversing the symbols of

, then taking the complement of each symbol (e.g., the reverse complement of “GTCA” is “TGAC”).

Given: A DNA string

of length at most 1000 bp.

Return: The reverse complement
of

.

Sample Dataset

AAAACCCGGT

Sample Output

ACCGGGTTTT

def reverse_complement(seq):
      """
       生成反向互补序列
       :param seq:
       :return:revComSeq
       """
       ATCG_dict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C', 'a': 't', 't': 'a', 'c': 'g', 'g': 'c','N':'N'}
       revSeqList = list(reversed(seq))
       revComSeqList = [ATCG_dict[k] for k in revSeqList]
       revComSeq = ''.join(revComSeqList)
       return revComSeq
    
seq = 'AAAACCCGGT'
output = reverse_complement(seq)
print(output)
ACCGGGTTTT
def reverseComplement(seq):
      """
       生成反向互补序列
       :param seq:
       :return:revComSeq
       """
       ATCG_dict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C', 'a': 't', 't': 'a', 'c': 'g', 'g': 'c', 'N': 'N'}
       revComSeq = ''
       for i in seq:
           revComSeq =  ATCG_dict[i] + revComSeq
       return revComSeq

seq = 'AAAACCCGGT'
output = reverseComplement(seq)
print(output) 
ACCGGGTTTT

Rabbits and Recurrence Relations/斐波那契数列

Problem

A sequence is an ordered collection of objects (usually numbers), which are allowed to repeat. Sequences can be finite or infinite. Two examples are the finite sequence ( π , 2 , 0 , π ) (\pi,\sqrt2,0,\pi) and the infinite sequence of odd numbers ( 1 , 3 , 5 , 7 , . . . ) (1,3,5,7,...) We use the notation a n a_n to represent the n n -th term of a sequence.

A recurrence relation is a way of defining the terms of a sequence with respect to the values of previous terms. In the case of Fibonacci’s rabbits from the introduction, any given month will contain the rabbits that were alive the previous month, plus any new offspring. A key observation is that the number of offspring in any month is equal to the number of rabbits that were alive two months prior. As a result, if F n F_n represents the number of rabbit pairs alive after the n n -th month, then we obtain the Fibonacci sequence having terms F n F_n that are defined by the recurrence relation F n = F n 1 + F n 2 F_n = F_{n-1} + F_{n-2} (with F 1 = F 2 = 1 F_1 = F_2 = 1 to initiate the sequence). Although the sequence bears Fibonacci’s name, it was known to Indian mathematicians over two millennia ago.

When finding the
-th term of a sequence defined by a recurrence relation, we can simply use the recurrence relation to generate terms for progressively larger values of n n

. This problem introduces us to the computational technique of dynamic programming, which successively builds up solutions by using the answers to smaller cases.

Given: Positive integer n < = 40 n<= 40 and k < = 5 k <= 5

Return: The total number of rabbit pairs that will be present after n n months, if we begin with 1 pair and in each generation, every pair of reproduction-age rabbits produces a litter of k k rabbit pairs (instead of only 1 pair).

每对兔子在成年阶段每个月能产生1对幼年兔子

F 1 = 1 , F 2 = 1 , F 3 = F 2 + F 1 F_1 = 1, F_2 = 1, F_3 = F_2 + F_1

月份 1 2 3 4 5 6
兔子个数(对) 1 1 2 3 5 8

每对兔子在成年阶段每个月能产生3对幼年兔子
F 1 = 1 , F 2 = 1 , F 3 = F 2 + F 1 × 3 F_1 = 1, F_2 = 1, F_3 = F_2 + F_1 \times 3

月份 1 2 3 4 5 6
兔子个数(对) 1 1 4 7 19 40

Sample Dataset

5 3

Sample Output

19

def fibonacciRabbits(n, k):
    F = [1, 1]
    generation = 2
    while generation < n:
        F.append(F[generation - 1] + F[generation - 2] * k)
        generation += 1
    return F[n-1]


print(fibonacciRabbits(5, 3))
19
def fibonacciRabbits(n, k):
    if n <= 2:
        return 1
    else:
        return fibonacciRabbits(n-1, k) + fibonacciRabbits(n-2, k) * k


print(fibonacciRabbits(5, 3))
19
def fibonacciRabbits(n, k):
    generation, a, b = 2, 1, 1
    while generation <= n:
        yield b
        a, b = b, a*k+b
        generation += 1
    return 'well done'


fib = fibonacciRabbits(5, 3)
print(list(fib)[-1])
19

Computing GC Content/计算序列GC含量

Problem

The GC-content of a DNA string is given by the percentage of symbols in the string that are ‘C’ or ‘G’. For example, the GC-content of “AGCTATAG” is 37.5%. Note that the reverse complement of any DNA string has the same GC-content.

DNA strings must be labeled when they are consolidated into a database. A commonly used method of string labeling is called FASTA format. In this format, the string is introduced by a line that begins with ‘>’, followed by some labeling information. Subsequent lines contain the string itself; the first line to begin with ‘>’ indicates the label of the next string.

In Rosalind’s implementation, a string in FASTA format will be labeled by the ID “Rosalind_xxxx”, where “xxxx” denotes a four-digit code between 0000 and 9999.

Given: At most 10 DNA strings in FASTA format (of length at most 1 kbp each).

Return: The ID of the string having the highest GC-content, followed by the GC-content of that string. Rosalind allows for a default error of 0.001 in all decimal answers unless otherwise stated; please see the note on absolute error below.

Sample Dataset

>Rosalind_6404
CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCC
TCCCACTAATAATTCTGAGG
>Rosalind_5959
CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCT
ATATCCATTTGTCAGCAGACACGC
>Rosalind_0808
CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGAC
TGGGAACCTGCGGGCAGTAGGTGGAAT

Sample Output

Rosalind_0808
60.919540

def gc_content(seq):
    """
    GC含量
    :param seq: 序列
    :return:
    """
    GC = (seq.upper().count('G') + seq.upper().count('C')) / len(seq) * 100
    return GC


def read_fasta(fastaFile):
    """读取fasta文件"""
    aDict = {} 
    for line in open(fastaFile,'r', encoding='utf-8'): 
        if line[0] == '>': 
            key = line.split()[0][1:] 
            aDict[key] = [] 
        else: 
            aDict[key].append(line.strip())
    return aDict


if __name__ == '__main__':
    seqName = 'Rosalind_0808'
    fastaFile = "./data/test3.fa"   

    fastaSeq = read_fasta(fastaFile)[seqName]
    GC = gc_content(''.join(fastaSeq))

    print(seqName)
    print('%.6f' % GC)     

Rosalind_0808
60.919540

计算GC含量最大的DNA序列

from operator import itemgetter


def gc_content(seq):
    """
    GC含量
    :param seq: 序列
    :return:
    """
    GC = (seq.upper().count('G') + seq.upper().count('C'))/len(seq)*100
    return GC


def read_fasta(fastaFile):
    """读取fasta文件"""
    seqDict = {} 
    for line in open(fastaFile,'r', encoding='utf-8'): 
        if line[0] == '>': 
            key = line.split()[0][1:] 
            seqDict[key] = [] 
        else: 
            seqDict[key].append(line.strip())
    return seqDict



if __name__ == '__main__':
    gcDict ={}
    fastaFile = "./data/test3.fa"   
    seqDict = read_fasta(fastaFile)
    for key, val in seqDict.items():
        gcDict[key] = gc_content(''.join(val))
    gcDictSort = sorted(gcDict.items(), key = itemgetter(1), reverse = True)
    name = gcDictSort[0][0]
    largeGC = gcDictSort[0][1]
    print(gcDictSort)
    print('%s : %.6f' % (name,largeGC))    

[('Rosalind_0808', 60.91954022988506), ('Rosalind_6404', 53.75), ('Rosalind_5959', 53.57142857142857)]
Rosalind_0808 : 60.919540

刷题ROSALIND,练编程水平

猜你喜欢

转载自blog.csdn.net/sunchengquan/article/details/85038894