我有一個問題,我有一個包含類物件的字典,它參考了一個或多個專案。字典的鍵是每個專案的 id。我正在嘗試為 x 步設定一個遞回函式來查找相鄰專案 ID 鏈。
它有效,但前提是每個“adjacent_items”變數中只有一個專案。如果還有更多,它仍然只捕獲第一個并繼續前進。在示例中,從未處理過“7”。
我對遞回函式很陌生,但我覺得應該有一種有效的方法,所以用遞回來解決這個問題。任何輸入將不勝感激。
class Item:
def __init__(self, id_num: str, adjacent: list):
self.id = id_num
self.adjacent_items = adjacent
def get_adjacent_x_steps(start: str, item_dict: dict, x: int, wip_set=None):
"""Get adjacent items for x steps"""
if wip_set is None:
wip_set = set()
if x != 0:
x -= 1
for item in item_dict[start].adjacent_items:
wip_set.add(item)
# Todo, only takes first hit, return exits this instance..
return get_adjacent_x_steps(item, item_dict, x, wip_set)
else:
return wip_set
def example():
"""Example items"""
item1 = Item("1", ["4", "7"])
item2 = Item("4", ["5"])
item3 = Item("7", ["5"])
item4 = Item("5", ["8", "17"])
item_dict = {}
for item in (item1, item2, item3, item4):
item_dict[item.id] = item
chained_items = get_adjacent_x_steps("1", item_dict, 2)
print(chained_items)
if __name__ == '__main__':
example()
uj5u.com熱心網友回復:
請嘗試以下操作:
class Item:
def __init__(self, id_num: str, adjacent: list):
self.id = id_num
self.adjacent_items = adjacent
def get_adjacent_x_steps(start, item_dict, x):
if x == 0 or start not in item_dict:
return [[]]
return [[adj, *lst]
for adj in item_dict[start].adjacent_items
for lst in get_adjacent_x_steps(adj, item_dict, x - 1)]
item1 = Item("1", ["4", "7"])
item2 = Item("4", ["5"])
item3 = Item("7", ["5"])
item4 = Item("5", ["8", "17"])
item_dict = {i.id: i for i in (item1, item2, item3, item4)}
print(get_adjacent_x_steps('1', item_dict, 1))
print(get_adjacent_x_steps('1', item_dict, 2))
print(get_adjacent_x_steps('1', item_dict, 3))
遞回發生在串列理解中;at start,獲取所有相鄰項(for adj in item_dict[start].adjacent_items),并將函式應用于那些少一步的項(get_adjacent_x_steps(adj, item_dict, x - 1))。然后將結果串列lst與 一起回傳adj。
輸出:
[['4'], ['7']]
[['4', '5'], ['7', '5']]
[['4', '5', '8'], ['4', '5', '17'], ['7', '5', '8'], ['7', '5', '17']]
如果你想得到一組目的地,那么你可以在之后應用一個集合理解:
print({x[-1] for x in get_adjacent_x_steps('1', item_dict, 3)})
# {'17', '8'}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359900.html
下一篇:遞回中的全域計數器
