首页 > 解决方案 > 滑动窗口和识别列表中的特定字符

问题描述

说明:编写一个脚本,根据可调整大小的滑动窗口计算 dna 字符串的 %GC。所以说窗口的长度是 L = 10 个碱基,那么你将沿着 dna 链从位置 0 移动窗口到末端(小心,不要太远......)并将碱基“提取”成一个子串并分析GC含量。将数字放入列表中。dna 字符串可能非常大,因此您需要从输入文件中读取字符串,并将结果打印到逗号分隔的输出文件中,该输出文件可以移植到 Excel 中进行绘图。

对于最终的数据分析,使用 L = 100 的窗口并分析文件中的两个基因组:Bacillus_amyloliquefaciens_genome.txt Deinococcus_radiodurans_R1_chromosome_1.txt

但首先,要让您的脚本正常运行,请使用以下训练器数据集。让窗口 L=4。示例输入和输出如下:

输入:AACGGTT

输出:

0,0.50
1,0.75
2,0.75
3,0.50

我的代码:

dna = ['AACGGTT']
def slidingWindow(dna,winSize,step):
    """Returns a generator that will iterate through
    the defined chunks of input sequence.  Input sequence
    must be iterable."""

    # Verify the inputs
    #try: it = iter(dna)
   # except TypeError:
    #raise Exception("**ERROR** sequence must be iterable.")
    if not ((type(winSize) == type(0)) and (type(step) == type(0))):
        raise Exception("**ERROR** type(winSize) and type(step) must be int.")
    if step > winSize:
        raise Exception("**ERROR** step must not be larger than winSize.")
    if winSize > len(dna):
        raise Exception("**ERROR** winSize must not be larger than sequence length.")

    # Pre-compute number of chunks to emit
    numOfwins = ((len(dna)-winSize)/step)+1

    # Do the work
    for i in range(0,numOfwins*step,step):
        yield dna[i:i+winSize]
        chunks = slidingWindow(dna,len(dna),step)
        for y in chunks:
            total = 1 
            search = dna[y]
            percentage = (total/len(dna))
            if search == "C":
                        total = total+1
                        print ("#", y,percentage)
            elif search == "G":
                        total = total+1
                        print ("#", y,percentage)
            else:
                    print ("#", y, "0.0")

"""
MAIN
calling the functions from here
"""

#    YOUR WORK HERE
#print ("#", z,percentage)

标签: python-3.x

解决方案


在处理复杂问题时,将其划分为更简单的子问题会很有帮助。在这里,您至少有两个独立的概念:基础窗口和此类窗口上的统计信息。你为什么不一次解决一个呢?

这是一个简单的生成器,可以生成所需大小的块:

def get_chunks(dna, window_size=4, stride=1):
    for i in range(0, len(dna) - window_size + 1, stride):
        chunk = dna[i:i + window_size]
        assert len(chunk) == window_size
        yield chunk


for chunk in get_chunks('AACGGTT'):
    print(chunk)

它显示此输出:

AACG
ACGG
CGGT
GGTT

现在,有了这些,你能不能写一个简单的函数来接受一个四字符的字符串并产生一个适当的统计摘要?[请将其作为您问题的单独答案发布。是的,一开始可能听起来很奇怪,但 StackOverflow确实鼓励你发布问题的答案,这样你就可以分享你学到的东西。]


推荐阅读