Practice: Most Common Word

Practice: Most Common Word

This exercise combines lower, split, and Counter — the word-frequency problem from the dictionaries section, now with the standard library doing the counting.

Exercise

  1. Define a function named most_common_word with one parameter, text (non-empty).
  2. It returns the most frequent word, compared case-insensitively.

most_common_word("The cat saw the dog") returns "the".

Run your code to see the output, then press Submit.

Hints

  • Lowercase, split, wrap in Counter, then most_common(1).
  • most_common(1) returns a list holding one (word, count) tuple — index into it.

Tests

import unittest


class TestMostCommonWord(unittest.TestCase):
    def test_the_wins_across_cases(self):
        self.assertEqual(most_common_word("The cat saw the dog"), "the")

    def test_single_word(self):
        self.assertEqual(most_common_word("hello"), "hello")

    def test_clear_majority(self):
        self.assertEqual(most_common_word("go stop go go stop"), "go")
from collections import Counter


def most_common_word(text):
    counts = Counter(text.lower().split())
    return counts.most_common(1)[0][0]


print(most_common_word("The cat saw the dog"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.