Design a Food Rating System LeetCode solution in Python

1
from heapq import heapify, heappop, heappush
2

3

4
class RatedFood:
5
def __init__(self, rating, food):
6
self.rating = rating
7
self.food = food
8

9
def __lt__(self, other):
10
if other.rating == self.rating:
11
return self.food < other.food
12
return self.rating < other.rating
13

14

15
class FoodRatings:
16
def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
17
self.cuis_to_score_heap = defaultdict(list)
18
self.food_to_latest_ratings = defaultdict(int)
19
self.food_to_cuis = defaultdict(str)
20

21
for food, cuis, rating in zip(foods, cuisines, ratings):
22
self.food_to_cuis[food] = cuis
23
self.food_to_latest_ratings[food] = rating
24
heappush(self.cuis_to_score_heap[cuis], RatedFood(-rating, food))
25

26
def changeRating(self, food: str, newRating: int) -> None:
27
self.food_to_latest_ratings[food] = newRating
28
cuis = self.food_to_cuis[food]
29
heappush(self.cuis_to_score_heap[cuis], RatedFood(-newRating, food))
30

31
def highestRated(self, cuisine: str) -> str:
32
while True:
33
ratedFood = heappop(self.cuis_to_score_heap[cuisine])
34
if self.food_to_latest_ratings[ratedFood.food] == (-ratedFood.rating):
35

36
# because the food item is still valid, we put it back into the heap
37
heappush(self.cuis_to_score_heap[cuisine], ratedFood)
38

39
return ratedFood.food

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0