Design and implement a web browser that supports the functionality that at any given instance you can efficiently tell the top 5 visited websites on basis of the number of visits (in any order)
In my implementation, I did not use the Webpage class as I can't think of an efficient way we could update the heap based on visits unless we did heapify again. I don't think I can update the heap "on the go". If I use the Webpage class to track visits instead of the hashtable I would still need to update the hashtable every time I visit a site.
I want to understand how I can optimize this solution in PYTHON. I have seen implementations in C++, but I want to know if I can optimize my current implementation in my language of choice. Any insight would be great.
class Webpage:
def __init__(url):
self.url = url
self.numberOfVisits = 1
class History:
def _init_():
self.sites = {}
def visit(url):
if (url in self.sites):
self.sites[url] += 1
else:
self.sites[url] = 1
def printTop5():
heap = []
heapq.heapify(heap)
for key, value in self.sites:
heap.heappush(heap, (-value, key))
i = 0
while (heap and i < 5):
value, url = heapq.heappop(heap)
print(url)
i += 1
def main():
History h = History();
print("before visits\n")
h.visit("www.google.com")
h.visit("nytimes.com")
h.visit("reddit.com")
h.visit("dev.ibm.com")
h.visit("www.google.com")
print("after visits\n")
h.printTop5()
h.visit("ig.com")
h.visit("ig.com")
h.visit("ig.com")
h.printTop5()