我写了一个函数,用于返回一个生成器,其中包含每个唯一组合的子字符串,其长度为给定长度且包含来自主字符串的n个以上元素。
举个例子:
如果我有'abcdefghi',探针长度为2,阈值为每个列表4个元素,我希望得到:
如果将yield更改为print,则可以正常工作!我将不胜感激,如果能得到任何帮助。我意识到这不是这种搜索问题的最佳实现方式,似乎从get_next_probe的最后一次调用返回找到的位置列表,并过滤不重叠new_last_probe.end的元素,会更加高效...但这对我来说更容易编写。仍然欢迎任何算法输入。
谢谢!
举个例子:
如果我有'abcdefghi',探针长度为2,阈值为每个列表4个元素,我希望得到:
['ab', 'cd', 'ef', 'gh']
['ab', 'de', 'fg', 'hi']
['bc', 'de', 'fg', 'hi']
我第一次尝试解决这个问题时,返回了一个列表的列表。结果导致计算机的内存溢出。作为一种粗糙的备选方案,我创建了一个类似的生成器。问题是我创建了一个调用自身的嵌套生成器。当我运行这个函数时,它似乎只是在内部循环中循环而没有实际调用自身。我以为生成器会一直向下递归到达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
如果将yield更改为print,则可以正常工作!我将不胜感激,如果能得到任何帮助。我意识到这不是这种搜索问题的最佳实现方式,似乎从get_next_probe的最后一次调用返回找到的位置列表,并过滤不重叠new_last_probe.end的元素,会更加高效...但这对我来说更容易编写。仍然欢迎任何算法输入。
谢谢!