python练习题1 计算多个DNA序列中,GC比最高的序列

这是题目连接: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)


解决思路2: 可以通过嵌套列表实现对GC比的排序,从而得到GC含量最高的序列

代码如下:

#!/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])



  • 7
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值