私は食品とレストランのオブジェクトのコレクションを持っており、私はすべてのオブジェクトの食品オブジェクトを対応するレストランに一致させる必要があります。 時間複雑度O(n * m)を持つ素朴な解を実装しました。ここでnとmはそれぞれ食品データベースとレストランデータベースのサイズです。Pythonで条件付きで2つのデータベースを一致
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"]
メソッド食品()やレストランが()ジェネレータです。 どうすればこのアルゴリズムを高速化できますか?
'foods()'と 'restaurants()'は特定の順序で内容を出力しますか?多分 'id'を' Structure'に写像するディクショナリを使っているので、リストの1つを一度しか反復する必要はありません。 –
これは素晴らしいです!ありがとうございました。ソリューションは簡単でした。俺はバカです! – user1877600