我在Python中有一个基本的问题,在那里我必须验证我的回溯代码是否找到了一些解决方案(我必须找到所有带有属性n的1到|x[i] - x[i-1]| == m数字的子列表)。如何检查是否有解决方案?我的意思是我找到的潜在解决方案,我只是打印它们,而不是将它们保存在内存中。如果没有解决办法,我必须打印一条正确的信息。
发布于 2015-12-28 16:30:50
正如我在注释中所建议的,您可能希望将计算与I/O打印分离,方法是创建|x[i] - x[i-1]| == m解决方案的生成器。
让我们假设您定义了一个生成解决方案的生成器:
def mysolutions(...):
....
# Something with 'yield', or maybe not.
....下面是一个生成器装饰符,您可以使用它来检查实现的生成器是否有一个值。
from itertools import chain
def checkGen(generator, doubt):
"""Decorator used to check that we have data in the generator."""
try:
first = next(generator)
except StopIteration:
raise RuntimeError("I had no value!")
return chain([first], generator)使用此装饰器,您现在可以使用以下方法定义以前的解决方案:
@checkGen
def mysolutions(...):
....然后,您可以简单地使用它来分离您的I/O:
try:
for solution in mysolutions(...):
print(solution) #Probably needs some formatting
except RuntimeError:
print("I found no value (or there was some error somewhere...)")https://stackoverflow.com/questions/34496977
复制相似问题