我编写了一个函数来返回一个生成器,其中包含给定长度的子字符串的每个唯一组合,这些子字符串包含主字符串中的 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 的元素会更有效...但这对我来说写起来容易多了。任何算法输入仍将受到赞赏。
Thanks!