2015-12-28 26 views
0

我有一個Python的基本問題,我必須驗證我的回溯代碼是否找到了一些解決方案(我必須找到屬性爲|x[i] - x[i-1]| == m的所有1到n數字的子列表)。我如何檢查是否有解決方案?我的意思是我找到的潛在解決方案,我只是打印它們,而不是將它們保存到內存中。如果沒有解決方案,我必須打印適當的消息。Python backtracking

+0

也許從我分解計算/ O操作(這裏是打印),通過實現一個生成器。然後你可以檢查你的發電機是否至少有第一個值。 – DainDwarf

回答

0

正如我在評論所說,你可能需要從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...)")