如何在任何给定时间点从给定字符串中找到前10个单词。蟒蛇

时间:2018-07-22 09:04:21

标签: python algorithm data-structures

可以说我有一个字符串s,并且在任何给定时间点,单词都会不断添加到该字符串中。现在,我必须在任何给定的时间点保持前10个重复出现的单词。

我的方法是创建一个具有键值对的字典,如下所示。

dic = {}
for i in s:
   if i in dic:
      dic[i] +=1
   else:
      dic[i] = 1

现在我想保持以上字典中前10个单词的频率。 我可以执行上述操作的可能方式是

  1. 我可以在每次迭代后对字典进行排序,但是由于字典可能包含数百万条记录,因此这将导致很高的复杂性。
  2. 我可以使用计数器或集合的功能,但是我不想使用任何内置函数。

我希望以上程序在线性时间内工作。我知道上述问题曾被问过,但我找不到线性解。

2 个答案:

答案 0 :(得分:1)

您不需要每次都对整个字典进行排序。只需检查增量值现在是否大于现有的第十个最大值即可。

答案 1 :(得分:0)

这就是我能够实现所要询问的内容的方式。

file = open('read.txt','r')
text = file.read().split()
word_cout = {}
top_words = {}
for i in text:
    if i in word_cout:
        word_cout[i] +=1
    else:
        word_cout[i] = 1
    if i not in top_words:
        for key in top_words.copy():
            if top_words[key] < word_cout[i]:
                top_words.pop(key)
                top_words[i] = word_cout[i]
                break
    if(len(top_words) < 10):
        top_words[i] = word_cout[i]

# print(word_cout)
print((top_words))