Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1#!/usr/bin/env python3 

2"""Solution to chapter 3, exercise 12: most_repeating_word""" 

3 

4from collections import Counter 

5import operator 

6 

7WORDS = ['this', 'is', 'an', 'elementary', 'test', 'example'] 

8 

9 

10def most_repeating_letter_count(word): 

11 """Given a non-empty string, counts how 

12many times each letter appears in the string, 

13and returns an integer indicating how often 

14the most common letter appears.""" 

15 return Counter(word).most_common(1)[0][1] 

16 

17 

18def most_repeating_word(words): 

19 """Given a list of non-empty strings (words), 

20returns the word containing at least one letter that repeats 

21more often than any letter in any other word. 

22 

23Because sorting in Python is stable, if multiple words have 

24the same count, then the first will be returned.""" 

25 word_counts = {word: most_repeating_letter_count(word) 

26 for word in words} 

27 

28 return max(word_counts.items(), key=operator.itemgetter(1))[0]