This exercise combines lower, split, and Counter — the word-frequency problem from the dictionaries section, now with the standard library doing the counting.
most_common_word with one parameter, text (non-empty).most_common_word("The cat saw the dog") returns "the".
Run your code to see the output, then press Submit.
Counter, then most_common(1).most_common(1) returns a list holding one (word, count) tuple — index into it.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"))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.