这是题目连接:http://rosalind.info/problems/gc/
解决思路可以有多种,下面提供我想到的两种解决思路。
解决思路1.可以通过collections模块中的OrderedDict,将字典排序,。从而找到GC比最高的序列:
下面是代码:
#!/usr/bin/env python
#_*_ coding: utf-8 _*
from operator import itemgetter
from collections import OrderedDict
#创建一个有序字典集合,根据输入的先后顺序排序
seqTest = OrderedDict()
gcCountent = OrderedDict()
with open('E:\\bioinfo\study\data\\test5.txt','r') as input_file:
#逐行读取输入文件
for line in input_file:
line = line.rstrip() #删除字符串末尾的指定字符,默认为空格
#将DNA序列信息保存在有序字典seqTest中
if line.startswith('>'):
seqName = line.strip('> ')
else:
seqTest[seqName] = line
for key, value in seqTest.items():
#生成一个包含GC含量的有序字典
seq_length = len(value)
GC_ratio = (float(value.count('C') + value.count('G'))) / seq_length
gcCountent[key] = GC_ratio
#将字典排序,根据每个元祖中的第二个元素排序
#将字典排序完之后,其形式也不为字典格式
gcCountent_sort = sorted(gcCountent.items(), key=itemgetter(1))
#取最大GC比
large_Name = gcCountent_sort[-1][0]
large_GCRation = gcCountent_sort[-1][1]
print 'GC比最大的DNA序列为:\n%s\n%.6f' % (large_Name, large_GCRation)
代码如下:
#!/usr/bin/env python
#_*_ coding: utf-8 _*
gcCount = []
def seq_GCRatio(sequence):
#输入含有序列信息的字符串,输出该序列中的GC比
GC_count = float(sequence.count('C') + sequence.count('G'))
seq_length = len(sequence)
GC_ratio = GC_count / seq_length * 100
return GC_ratio
with open('E:\\bioinfo\study\data\\test5.txt', 'r') as input_file:
for line in input_file:
seq_list = []
if line.startswith('>'):
seq_name = line.strip('[> | \n]')
else:
sequence = line.strip()
GC_ratio = seq_GCRatio(sequence)
seq_list.append(seq_name)
seq_list.append(GC_ratio)
gcCount.append(seq_list)
GC_Ratio_sort = sorted(gcCount, key=lambda x:x[1])
print 'GC比最高的序列为:\n%s\n%.6f' % (GC_Ratio_sort[-1][0], GC_Ratio_sort[-1][1])