You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写代码识别线性化RNA结构中茎环的起止位置?

问题分析与代码修正

你的代码当前会捕获每个">"块的第一个">",但我们需要的是每个">"块的最后一个">"。要解决这个问题,我们需要调整逻辑,等待遍历到">"块的末尾时再记录结束索引。

修正后的代码

RNA_SS = "..<<<<...>>>>..<<..>>"  
RNA_seq = "..AAUGCCCCAUU..CCAAGG" 

def id_stem_loops(consensus):
    stem_loops = []
    skip_sym = {".", ",", "-", "~", "_"}  # 用集合提升查找效率
    start_idx = None
    total_length = len(consensus)
    
    for idx, sym in enumerate(consensus):
        if sym in skip_sym:
            continue
        
        # 识别连续"<"块的起始位置
        if sym == "<":
            # 当前是"<"且前一个字符不是"<",说明是新的"<"块开始
            if idx == 0 or consensus[idx-1] != "<":
                start_idx = idx
        # 识别连续">"块的结束位置
        elif sym == ">":
            # 当前是">"且下一个字符不是">"(或已是最后一个字符),说明是">"块的结尾
            if idx == total_length - 1 or consensus[idx+1] != ">":
                if start_idx is not None:
                    stem_loops.append((start_idx, idx))
                    start_idx = None  # 配对完成后重置起始索引
    
    print(stem_loops)

id_stem_loops(RNA_SS)

关键逻辑调整

  1. 跟踪"<"块的起始:当遇到连续"<"的第一个字符时,记录其索引作为茎环的起始位置。
  2. 等待">"块的结束:只有当遍历到连续">"的最后一个字符时,才将之前记录的起始索引与当前索引配对,加入结果列表。
  3. 重置起始索引:每完成一个茎环的配对后,重置起始索引,确保下一个"<"块能正确被捕获。

运行修正后的代码,输出将是期望的 [(2, 12), (15, 20)]。

内容的提问来源于stack exchange,提问作者Kate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 12:52:39