![](/img/trans.png)
[英]Finding the maximum path sum from root to n-ary leaf in a tree if a negative node restarts the sum from 0
[英]finding the root node from tree data
我有以下課程:
class Category(object):
def __init__(self, *args, **kwargs):
self.id = kwargs.get('id')
self.name = kwargs.get('name')
self.parent_id = kwargs.get('parent_id', None)
def get_top_parent_category(self, obj_list):
# This algorithm is using extensive resource
category = self
while category.parent_id:
def filter_func(obj):
return obj.id == category.parent_id
parent = list(filter(filter_func, obj_list))
category = parent[0]
return category
@classmethod
def all(cls):
url = BASE_URL + '/api/v1/categories/'
response = requests.get(url, headers=headers, verify=False)
if not response.status_code == 200:
raise Exception('Error')
categories = response.json()
_temp_categories = []
for _i in categories['results']:
_temp_categories.append(cls(**_i))
return _temp_categories
我按以下方式獲取所有類別:
all_categories = Category.all()
現在,我需要找到提供的任何類別的根節點。
category = Category(**category_data)
category.get_top_parent_category(all_categories)
我得到了預期的結果,但是我覺得可能會有更好的方法使用圖論來找到根節點
解決這個問題的更好方法是什么?
如果您需要對其進行更多與樹相關的處理,則可能需要將Category對象彼此鏈接,而不是通過父標識符進行間接鏈接。
但是在您發布的代碼中,主要問題是這些重復的調用,您必須在其中掃描整個對象列表:
parent = list(filter(filter_func, obj_list))
如果將其替換為詞典,則性能會好很多,因為單親的查找時間為〜恆定時間
例如只是
parent_map = dict([(c.id, c) for c in obj_list])
(顯然,不要在get_top_parent_category()方法中執行此操作,因為它同樣昂貴)
然后,可以通過以下簡單方法查找類別的父項:
parent = parent_map[parent.id]
您現在擁有的同一循環將以這種方式快一個數量級。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.