【发布时间】:2012-05-03 02:45:49
【问题描述】:
我编写了一个函数来返回一个生成器,该生成器包含给定长度的子字符串的每个唯一组合,其中包含来自主字符串的 n 个以上元素。
作为说明:
如果我有 'abcdefghi' 和长度为 2 的探针,并且每个列表的阈值为 4 个元素,我想获得:
['ab', 'cd', 'ef', 'gh']
['ab', 'de', 'fg', 'hi']
['bc', 'de', 'fg', 'hi']
我对这个问题的第一次尝试涉及返回一个列表列表。这最终溢出了计算机的内存。作为粗略的辅助解决方案,我创建了一个执行类似操作的生成器。问题是我创建了一个调用自身的嵌套生成器。当我运行这个函数时,它似乎只是在内部 for 循环中循环,而实际上并没有再次调用它自己。我认为生成器会根据需要在递归漏洞之前尽可能远,直到它遇到 yield 语句。有什么线索吗?
def get_next_probe(self, current_probe_list, probes, unit_length):
if isinstance(current_probe_list, list):
last_probe=current_probe_list[-1]
available_probes = [candidate for candidate in probes if candidate.start>last_probe.end]
else:
available_probes = [candidate for candidate in probes if candidate.start<unit_length]
if available_probes:
max_position=min([probe.end for probe in available_probes])
available_probes2=[probe for probe in available_probes if max_position+1>probe.start]
for new_last_probe in available_probes2:
new_list=list(current_probe_list)
new_list.append(new_last_probe)
self.get_next_probe(new_list, probes, unit_length)
else:
if len(current_probe_list)>=self.num_units:
yield current_probe_list
如果将产量更改为打印,则效果很好!我会很感激我能得到的任何帮助。我意识到这不是此类搜索问题的最佳实现,似乎从 get_next_probe 的最后一次调用中返回找到的位置列表并过滤此列表以查找不重叠 new_last_probe.end 的元素会更有效率...但这对我来说写起来容易得多。任何算法输入仍将不胜感激。
谢谢!
【问题讨论】:
-
您似乎没有使用递归调用的结果。我希望看到一个内部循环遍历外部列表的子光照,将递归调用的结果连接起来形成产生的结果。
-
你也错过了第一行的报价,ab,
标签: python recursion generator bioinformatics