python-3.x - 滑动窗口和识别列表中的特定字符
问题描述
说明:编写一个脚本,根据可调整大小的滑动窗口计算 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)
解决方案
在处理复杂问题时,将其划分为更简单的子问题会很有帮助。在这里,您至少有两个独立的概念:基础窗口和此类窗口上的统计信息。你为什么不一次解决一个呢?
这是一个简单的生成器,可以生成所需大小的块:
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确实鼓励你发布问题的答案,这样你就可以分享你学到的东西。]
推荐阅读
- visual-studio-code - 使用 NET6 文件范围命名空间时,VS 代码中的语法高亮显示已关闭
- java - 如何从 Spring Boot 应用程序的文件夹作为 jar 运行主应用程序(不是 Spring Boot 应用程序)
- python - 如何在既不是 csv 文件也不是 Excel 文件的 pandas 中导入 URL?
- r - 在公式两侧使用 .data 代词的分面网格不起作用
- git - 如何禁用 Jenkins 结帐和 git 插件 SSL 验证?
- python - ValueError:无法将字符串转换为浮点数:(python)
- python - 按排序顺序处理文件
- kotlin - 在 kotlin 中,这种语法是什么:“fun ClassName.funcName(): (Type ) -> Type = {fun body}”
- java - 如何获得时间在 Android 中加载视频
- apache-iotdb - 无法在 Apache IoTDB 单元测试中删除 TsFile