我目前試圖理解組成示例的遞回。想象一下,你有一個公文包,可以用鑰匙打開。鑰匙在大箱子里,大箱子里可以裝其他小箱子,鑰匙可能在里面。
在我的示例中,框是串列。當我們找到較小的盒子時會出現遞回——我們搜索它的鍵。問題是我的函式可以找到鑰匙,如果它實際上在盒子里,如果沒有像“鑰匙”這樣的東西,就不能回去。
不幸的是,如果小盒子里沒有鑰匙,我無法理解如何回去。你能幫我解決這個難題嗎?順便說一句,祝你有美好的一天!這是代碼(大框包含可以找到和回傳密鑰的方式):
box = ['socks', 'papers', ['jewelry', 'flashlight', 'key'], 'dishes', 'souvernirs', 'posters']
def look_for_key(box):
for item in box:
if isinstance(item, list) == True:
look_for_key(item)
elif item == 'key':
print('found the key')
key = item
return key
print(look_for_key(box))
uj5u.com熱心網友回復:
迭代
我能找到的最接近你的但可讀的解決方案是:
def look_for_key(box):
for item in box:
if item == 'key':
return item
elif isinstance(item, list) and look_for_key(item) is not None:
return look_for_key(item)
else:
pass
box = [['sock','papers'],['jewelry','key']]
look_for_key(box)
# ==> 'key'
我不喜歡它,因為它的推導條件包括一個難以解釋的遞回呼叫。如果您分配look_for_key(item)給變數并not None隨后檢查,則無助于提高可解釋性。它同樣難以解釋。一個等效但更易解釋的解決方案是:
def look_for_key(box):
def inner(item, remained):
if item == [] and remained == []:
return None
elif isinstance(item, list) and item != []:
return inner(item[0], [item[1:], remained])
elif item == [] or item != 'key':
return inner(remained[0], remained[1:])
elif item == 'key':
return item
return inner(box[0], box[1:])
box = [['sock','papers'],['jewelry','key']]
look_for_key(box)
# ==> 'key'
它顯式地將樹拆分為分支(見下文,這意味著什么),return inner(item[0], [item[1:], remained])而return inner(remained[0], remained[1:])不是在推導期間有條件地重用遞回呼叫if look_for_key(item) is not None: return look_for_key(item)- 使用這行代碼很難看到圖表并理解遞回的方向。
第二種解決方案還可以更輕松地使用樹圖來推斷復雜性,因為您可以明確地看到分支,例如remained[0]vs. remained[1:].
由于inner只是以函式方式撰寫的迭代,而for回圈是形成迭代的語法糖,因此兩種解決方案原則上應該具有相似的復雜性。
由于您不僅想要一個解決方案,而且還想要更好地理解遞回,我會嘗試以下方法。
在樹上映射(Map-Reduce)
這是一個典型的教科書樹遞回問題。您想要的是遍歷稱為樹的分層資料結構。一個典型的解決方案是在樹上映射一個函式:
from functools import reduce
def look_for_key(tree):
def look_inner(sub_tree):
if isinstance(sub_tree, list):
return look_for_key(sub_tree)
elif sub_tree == 'key':
return [sub_tree]
else:
return []
return reduce(lambda left_branch, right_branch: look_inner(left_branch) look_inner(right_branch), tree, [])
box = ['socks', 'papers', ['jewelry', 'flashlight', 'key'], 'dishes', 'souvernirs', 'posters']
look_for_key(box)
# ==> ['key']
為明確起見,我使用tree, sub_tree, left_branch,right_branch作為變數名而不是box,inner_box等等,如您的示例中所示。注意函式如何look_for_key被映射在每個left_branch與right_branch該的sub_tree在S tree。然后使用reduce(經典的
Whenever the function got called recursively, the curve goes to a deeper level - the downward slash. When the tree/sub-tree is splitted to left and right branches, two calls happen at the same level - the horizontal line that connected two dots (two calls look_for_key(box[0]) look_for_key(box[1:])). When it traverses
over a complete sub-tree (or branch) and reaches to the last leave in that sub-tree (a base condition when a value or [] is returned), it starts to go back to upper levels - the valley in the curve. If you have multiple sub/nest lists there will be multiple valleys. Eventually it traverses over the whole tree and returns the results
您可以使用不同巢結構的盒子(或樹)來更好地了解它是如何作業的。希望這些為您提供足夠的資訊和對樹遞回的更全面的理解。
uj5u.com熱心網友回復:
綜合以上評論:
box = ['socks', 'papers', ['jewelry', 'flashlight', 'key'], 'dishes', 'souvernirs', 'posters']
def look_for_key(box):
for item in box:
if isinstance(item, list) == True:
in_box = look_for_key(item)
if in_box is not None:
return in_box
elif item == 'key':
print('found the key')
return item
# not found
return None
print(look_for_key(box))
列印:
found the key
key
如果密鑰從框中洗掉,則執行代碼列印:
None
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/383347.html
