Skip to content

Instantly share code, notes, and snippets.

@drio
Created September 10, 2014 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drio/354adff2b242b5dd9323 to your computer and use it in GitHub Desktop.
Save drio/354adff2b242b5dd9323 to your computer and use it in GitHub Desktop.
class Solution(object):
def __init__(self):
"""
h_items is a hash (key = item, value = number of items purchased (counts))
items_sorted is the list of items sorted by the counts
space cost: O(n*n) ~ O(n)
"""
self.h_items = {}
self.items_sorted = []
def itemPurchased(self, i_name):
"""
Since getRanking will be called more often, let's do the sorting of
the data right here.
time cost: O(nlog(n)) (Since python uses quicksort like internally)
"""
if i_name not in self.h_items:
self.h_items[i_name] = 0
self.h_items[i_name] += 1
self.__sort()
def getRanking(self):
"""
time cost: O(1)
"""
return self.items_sorted
def getTopTenProducts(self):
"""
time cost: O(1)
"""
return self.items_sorted[0:10]
def __sort(self):
"""
Convert the hash to a list and order by the counts.
Finally, update items_sorted by only keeping the items names
Time cost: O(nlog(n))
"""
self.items_sorted = []
for item, count in self.h_items.iteritems():
self.items_sorted.append([item, count])
self.items_sorted.sort(key=lambda i: i[1], reverse=True)
self.items_sorted = [e[0] for e in self.items_sorted]
solution_enable_basic_test = True
if solution_enable_basic_test:
s = Solution()
for i in range(0,20):
s.itemPurchased('i' + str(i))
s.itemPurchased('i1')
s.itemPurchased('i1')
assert(s.getRanking()[0] == 'i1')
s.itemPurchased('i2')
assert(s.getRanking()[1] == 'i2')
assert(len(s.getRanking()) == 20)
assert(len(s.getTopTenProducts()) == 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment