递归地通过字典
问题描述:
所以我有一本字典;递归地通过字典
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
但这并不使用递归,我不知道如何去
答
你可以试试这个:
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
你在哪里做你的程序中递归?递归意味着什么是根据自身定义的。但是在这里你不要在'function'里面调用'function'。 –
我没有在我的尝试中使用递归,所以我尝试使用字典comparingnsion –
你能解释为什么在你尝试构建一个字典并返回它? –