我有一個食物和餐廳的對象集合,我需要匹配所有對象食物對象到相應的餐廳。 我實現了一個天真的解決方案,其時間複雜度爲O(n * m),其中分別是食物和餐館數據庫的n和m大小。有條件地匹配python中的兩個數據庫
def match_products(self):
self._restaurant_dict= self._init_restaurant_dict()
for food in foods():
for restaurant in self._restaurant_dict.keys():
if self._matched(restaurant , food):
self.mached_candidates[restaurant].append(food)
def _init_restaurant_dict(self):
res_dict= {}
for product in restaurants():
res_dict[restaurant] = []
return res_dict
def _matched(self, restaurant , food):
return restaurant.id == food.id
餐廳和食品的定義如下:
class Structure:
_fields = []
def __init__(self, *args):
if len(args) != len(self._fields):
raise TypeError("Wrong args number")
for name, val in zip(self._fields,args):
setattr(self, name, val)
def __repr__(self):
return ', '.join("%s: %s" % item for item in vars(self).items())
class Restaurant(Structure):
_fields = ["id","name","owner"]
class Food(Structure):
_fields = ["id","descriptions","calories"]
方法食品()和餐館()是發電機。 那麼我該如何加快這個算法呢?
「食物()」和「餐館()」是否以任何特定的順序產生其內容?也許使用將'id'映射到'Structure'的字典,所以你只需要遍歷其中一個列表。 –
這真棒!謝謝。所以解決方案非常簡單。我是個傻瓜! – user1877600