返回访问量最大的5个网站(堆、哈希表)Python

2024-04-24 06:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

设计并实现一个web浏览器,该浏览器支持在任何给定实例中都可以使用的功能 您可以根据访问次数(以任何顺序)高效地说出访问量最大的5个网站。

在我的实现中,我没有使用Webpage类,因为我想不出一种基于访问更新堆的有效方法,除非我们再次进行heapify。我认为我不能“在路上”更新堆。如果我使用Webpage类来跟踪访问,而不是使用哈希表,那么每次访问站点时仍然需要更新哈希表

我想了解如何用PYTHON优化此解决方案。我已经看到C++中的实现,但是我想知道我是否可以用我选择的语言来优化当前的实现。任何洞察都会很好

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()

Tags: selfcomurlvaluedef浏览器visithistory
1条回答
网友
1楼 · 发布于 2024-04-24 06:32:18

从技术上讲,在Python中实现这一点的最佳方法是使用内置的collections.Counter数据类型。这是用高度优化的代码编写的,可能会产生Python可能的最佳性能。您可以在文档[此处](https://docs.python.org/3/library/collections.html#collections.Counter)中阅读更多关于它的信息

例如:

from collections import Counter

history = Counter()

#I made them one by one to signify individal browser requests
history["google.com"] += 1
history["yahoo.com"] += 1
history["spotify.com"] += 1
history["yahoo.com"] += 1
history["bing.com"] += 1
history["youtube.com"] += 1
history["amazon.com"] += 1
history["yahoo.com"] += 1
history["google.com"] += 1
history["wikipedia.com"] += 1
history["wikipedia.com"] += 1
history["yahoo.com"] += 1
history["yahoo.com"] += 1
history["amazon.com"] += 1

print(history.most_common(5))

这将返回:

[('yahoo.com', 5), ('google.com', 2), ('amazon.com', 2), ('wikipedia.com', 2), ('spotify.com', 1)]

由于这是Python的标准安装,我认为这应该算作“”Python

相关问题 更多 >