问题描述
Problem
A matrix is a rectangular table of values divided into rows and columns. An m × n m \times n m×n matrix has m m m rows and n n n columns. Given a matrix A A A, we write A i , j A_{i, j} Ai,j to indicate the value found at the intersection of row i i i and column j j j.
Say that we have a collection of DNA strings, all having the same length n n n. Their profile matrix is a 4 × n 4 \times n 4×n matrix P P P in which P 1 , j P_{1,j} P1,j represents the number of times that ‘A’ occurs in the j j jth position of one of the strings, P 2 , j P_{2,j} P2,j represents the number of times that C occurs in the j j jth position, and so on (see below).
A consensus string c c c is a string of length n n n formed from our collection by taking the most common symbol at each position; the j j jth symbol of c c c therefore corresponds to the symbol having the maximum value in the j j j-th column of the profile matrix. Of course, there may be more than one most common symbol, leading to multiple possible consensus strings.
DNA Strings
A T C C A G C T
G G G C A A C T
A T G G A T C T
A A G C A A C C
T T G G A A C T
A T G C C A T T
A T G G C A C T
Profile
A 5 1 0 0 5 5 0 0
C 0 0 1 4 2 0 6 1
G 1 1 6 3 0 1 0 0
T 1 5 0 0 0 1 1 6
Consensus
A T G C A A C T
Given: A collection of at most 10 DNA strings of equal length (at most 1 kbp) in FASTA format.
Return: A consensus string and profile matrix for the collection. (If several possible consensus strings exist, then you may return any one of them.)
Sample Dataset
>Rosalind_1
ATCCAGCT
>Rosalind_2
GGGCAACT
>Rosalind_3
ATGGATCT
>Rosalind_4
AAGCAACC
>Rosalind_5
TTGGAACT
>Rosalind_6
ATGCCATT
>Rosalind_7
ATGGCACT
Sample Output
ATGCAACT
A: 5 1 0 0 5 5 0 0
C: 0 0 1 4 2 0 6 1
G: 1 1 6 3 0 1 0 0
T: 1 5 0 0 0 1 1 6
题目大意
给多串等长DNA序列,统计各位置不同碱基出现的次数,第一行输出各位置上最常见的碱基(如有多个,输出任意一个),接下来4行输出各位置各碱基出现的次数
题解
生成一个链表,每一项为一个字典,统计各位置各碱基出现的次数,最后输出即可
注意输入数据满足fasta格式,可能存在一个序列碱基有多行的情况,注意处理
参考代码
from Bio import SeqIO
l = 0
ans = []
for seq_record in SeqIO.parse("rosalind_cons.txt", "fasta"):
if (l == 0):
l = len(seq_record.seq)
for i in range(l):
ans.append({'A': 0, 'G': 0, 'C': 0, 'T':0})
for i in range(l):
ans[i][seq_record.seq[i]] += 1
with open("out.txt", "w") as fo:
for i in range(l):
fo.write(max(ans[i], key = ans[i].get))
fo.write('\n')
for j in ['A', 'C', 'G', 'T']:
fo.write("%s: " % j)
for i in range(l):
fo.write("%d " % ans[i][j])
fo.write("\n")
fo.close()