rosalind练习题十

# Problem

# A matrix is a rectangular table of values divided into rows and columns. An m×n matrix has m rows and n columns. Given a matrix A, we write Ai,j to indicate the value found at the intersection of row i and column j.

# Say that we have a collection of DNA strings, all having the same length n. Their profile matrix is a 4×n matrix P in which P1,j represents the number of times that 'A' occurs in the jth position of one of the strings, P2,j represents the number of times that C occurs in the jth position, and so on (see below).

# A consensus string c is a string of length n formed from our collection by taking the most common symbol at each position; the jth symbol of c therefore corresponds to the symbol having the maximum value in the j-th column of the profile matrix. Of course, there may be more than one most common symbol, leading to multiple possible consensus strings.

# 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序列集合中,每个位置出现次数最多的字符,将这些字符组合成一个新的字符串并称之为共识串。同时需要输出一个矩阵,矩阵的第i行第j列表示在i位置上的A,C,G,T出现的次数。

# 代码:

def consensus_and_profile(dna_strings):

# 计算每个位置上的字符出现次数

    profile = {'A': [0] *len(dna_strings[0]),

              'C': [0] *len(dna_strings[0]),

              'G': [0] *len(dna_strings[0]),

              'T': [0] *len(dna_strings[0])}

for dnain dna_strings:

for iin range(len(dna)):

profile[dna[i]][i] +=1

    # 生成共识串

    consensus =''

    for iin range(len(dna_strings[0])):

max_count =0

        max_char =''

        for charin ['A', 'C', 'G', 'T']:

if profile[char][i] > max_count:

max_count = profile[char][i]

max_char = char

consensus += max_char

return consensus, profile

# 读入数据集

data_file =open("input.txt", "r")

dna_strings = []

current_dna =''

for linein data_file:

if line[0] =='>':# 新的DNA序列开始

        if current_dna !='':

dna_strings.append(current_dna)

current_dna =''

    else:

current_dna += line.strip()

dna_strings.append(current_dna)# 最后一个DNA序列

data_file.close()

# 计算共识串和计数矩阵

consensus, profile = consensus_and_profile(dna_strings)

# 输出结果

print(consensus)

for charin ['A', 'C', 'G', 'T']:

print(char +':', ' '.join(str(x)for xin profile[char]))

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容