Skip to content

Commit 545854d

Browse files
authored
Create design-a-food-rating-system.py
1 parent 53b6137 commit 545854d

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Python/design-a-food-rating-system.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Time: ctor: O(nlogn)
2+
# changeRating: O(logn)
3+
# highestRated: O(1)
4+
# Space: O(n)
5+
6+
import collections
7+
import itertools
8+
from sortedcontainers import SortedList
9+
10+
11+
# sorted list
12+
class FoodRatings(object):
13+
14+
def __init__(self, foods, cuisines, ratings):
15+
"""
16+
:type foods: List[str]
17+
:type cuisines: List[str]
18+
:type ratings: List[int]
19+
"""
20+
self.__food_to_cuisine = {}
21+
self.__food_to_rating = {}
22+
self.__cusine_to_rating_foods = collections.defaultdict(SortedList)
23+
for food, cuisine, rating in itertools.izip(foods, cuisines, ratings):
24+
self.__food_to_cuisine[food] = cuisine
25+
self.__food_to_rating[food] = rating
26+
self.__cusine_to_rating_foods[cuisine].add((-rating, food))
27+
28+
def changeRating(self, food, newRating):
29+
"""
30+
:type food: str
31+
:type newRating: int
32+
:rtype: None
33+
"""
34+
old_rating = self.__food_to_rating[food]
35+
cuisine = self.__food_to_cuisine[food]
36+
self.__cusine_to_rating_foods[cuisine].remove((-old_rating, food))
37+
self.__food_to_rating[food] = newRating
38+
self.__cusine_to_rating_foods[cuisine].add((-newRating, food))
39+
40+
def highestRated(self, cuisine):
41+
"""
42+
:type cuisine: str
43+
:rtype: str
44+
"""
45+
return self.__cusine_to_rating_foods[cuisine][0][1]

0 commit comments

Comments
 (0)