The most elements in the statistical hash list of Python interview questions

  • 2021-12-04 19:11:44
  • OfStack

Problem

There is a sequence of elements. I want to know what is the element that appears the most in the sequence

Solutions

The Counter class in the collections module is transferred to the one designed by Ms. It even has a very handy most_common () method that tells us the answer directly.

To illustrate the usage, suppose there is a list of 1 series of words, and we want to find out which words appear most frequently.

Here's what we do:


words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
] 
from collections import Counter
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
# Outputs [('eyes', 8), ('the', 5), ('look', 4)]

It is discussed that any hashable object sequence can be provided to Counter objects as input. In the underlying implementation, Counter is a dictionary that maps elements to the number of times they occur. Example:


word_counter['not']
# 1
word_counter['eyes']
# 8

If you want to increase the count manually, you can simply increase it by yourself:


morewords = ['why','are','you','not','looking','in','my','eyes']
for word in morewords:
    word_counts[word] += 1 
print(word_counts['eyes'])
# 9

Another method is to use the update () method:


word_counts.update(morewords)

Counter objects can also be used in conjunction with various mathematical operations:


>>> a = Counter(words)
>>> b = Counter(morewords)
>>> a
Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2,
"you're": 1, "don't": 1, 'under': 1, 'not': 1})
>>> b
Counter({'eyes': 1, 'looking': 1, 'are': 1, 'in': 1, 'not': 1, 'you': 1,
'my': 1, 'why': 1})
>>> # Combine counts
>>> c = a + b
>>> c
Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2,
'around': 2, "you're": 1, "don't": 1, 'in': 1, 'why': 1,
'looking': 1, 'are': 1, 'under': 1, 'you': 1})
>>> # Subtract counts
>>> d = a - b
>>> d
Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2,
"you're": 1, "don't": 1, 'under': 1})

The above is the Python interview question statistics hash list of the most elements in the details, more about Python hash list of the most elements of statistics, please pay attention to other related articles on this site!


Related articles: