2017-11-10 138 views
0

所以我有一本字典;遞歸地通過字典

dictionary = {"one": ["two"], "two": ["three"], "three": [None]} 

我如何遞歸地通過函數來​​查找一個,如果我給三個? 例如:最終結果是三?是的,因爲一個 - >兩個 - >三個,並且相同。 3 - > 2 - > 1

到目前爲止,我已經嘗試在字典上使用列表理解;

def function(start, end, dict_to_check): 
    if dict_to_check[end] == start: 
     return True 
    else: 
     var = {key: value for key, value in dict_to_check.items() if value == start} 
     return var 

但這並不使用遞歸,我不知道如何去

+0

你在哪裏做你的程序中遞歸?遞歸意味着什麼是根據自身定義的。但是在這裏你不要在'function'裏面調用'function'。 –

+0

我沒有在我的嘗試中使用遞歸,所以我嘗試使用字典comparingnsion –

+0

你能解釋爲什麼在你嘗試構建一個字典並返回它? –

回答

0

你可以試試這個:

start = "one" 
end = "three" 
dictionary = {"one": ["two"], "two": ["three"], "three": [None]} 
def check(s): 
    if not dictionary[s][0]: 
    return "Not found" 
    if dictionary[s][0] == end: 
    return "found" 
    else: 
    return check(dictionary[s][0]) 


print(check(start)) 

輸出:

found