Write a function that finds the most frequently occurring word in a string.
most_common_word(text)
Words are separated by single spaces. If there's a tie, return whichever of the tied words appears first in text. Use collections.Counter.
most_common_word("the cat sat on the mat the cat ran") // → "the" (appears 3 times)
most_common_word("a a b b b c") // → "b" (appears 3 times)
most_common_word("x y z") // → "x" (all tied, x is first)
from collections import Counter
def most_common_word(text):
counts = Counter(text.split())
return counts.most_common(1)[0][0]
text.split() breaks the string into a list of words. Counter(...) takes that list and builds a count of how many times each word appears — this is the exact "counting dict" pattern you might build by hand with a regular dict, done for you in one call.
counts.most_common(1) returns a list containing the single most frequent entry, as a (word, count) tuple — for "the cat sat on the mat the cat ran", that's [("the", 3)]. Indexing [0] gets that one tuple, and [0] again gets the word out of the tuple (index 0 of ("the", 3) is "the"; index 1 would be the count 3).
When multiple words are tied for the most common, most_common() breaks the tie by insertion order — the word that was counted first (i.e., appeared first in the original text) comes first in the result. That's why "x y z" (all appearing once, all tied) returns "x": it's simply the first one Counter encountered while scanning the text.
from collections import Counter
def most_common_word(text):
counts = Counter(text.split())
return counts.most_common(1)[0][0]
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.