We know that the collections of the python built-in module has a lot of useful operations.
for example:
from collections import Counter
-sharp
-sharp top n
user_counter = Counter("abbafafpskaag")
print(user_counter.most_common(3)) -sharp[("a", 5), ("f", 2), ("b", 2)]
print(user_counter["a"]) -sharp 5
how would you implement it with js? Or is there a built wheel with such an operation in it?
implement most_common: in python
def most_common(self, n=None):
"""List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter("abcdeabcdabcaba").most_common(3)
[("a", 5), ("b", 4), ("c", 3)]
"""
-sharp Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
A _ heapq
heap data structure is used here, which means that it is a heap to solve the top n problem, not to traverse it. What are the similar wheels for js
"Note:" the traversal method can be implemented by str.split ()
.
in fact, the essence of this problem is using heap to implement Top K algorithm (JS implementation)