以最佳时间复杂度获取列表中最常出现的5个元素

时间:2018-10-19 12:50:34

标签: python time element complexity-theory

我正在尝试将5个最常见的元素及其出现次数从列表中排除。我用一个可以解决时间复杂度O(5 * n * n)的解决方案解决了这个问题。

有没有更好的时间复杂度的最佳解决方案?

示例输入:

[['16.37.123.153','119.222.456.130','38673','161','17','62','4646']
 ['16.37.456.153','119.222.123.112','56388','161','17','62','4646']..]

示例输出:

MostOccurrentElements = [['16.37.123.153','119.222.456.130','38673','161','17','62','4646']..]
Counter = [134, ..]

“ MostOccurrentElements List”的第一个元素与“ Counter List”的第一个元素一起出现。

1 个答案:

答案 0 :(得分:1)

您可以使用heapq.nlargest方法来获取O(n log(t))时间复杂度最高的5个项目,其中n是项目数,t是要获取的最大项目数。 collections.Counter可以在O(n)的时间内获得每个不同项目值的计数,因此总体上,以下代码可以在O(n log(t))的平均值中找到5个最常出现的项目:

from collections import Counter
import heapq
from operator import itemgetter
l = [1,1,2,3,3,3,3,4,4,4,4,5,5,6,6,6,7]
print(heapq.nlargest(5, Counter(l).items(), key=itemgetter(1)))

这将输出:

[(3, 4), (4, 4), (6, 3), (1, 2), (5, 2)]

编辑:正如@jpp在评论中指出的那样,可以使用most_common中的等效包装器方法Counter完成以上操作:

print(Counter(l).most_common(5))