cswork / libraryOpen practice workspace

Coding questions · PayPal

Count Word Frequency and Print Top Three Words

This question evaluates proficiency in basic Python programming, string/text processing, frequency counting and sorting algorithms, reflecting core competencies for data manipulation tasks.

Scenario

First-round Python coding screening

Question

Using only basic Python, write a function that receives a list of strings and returns a dictionary mapping each unique word to its frequency. Then print the three most frequent words in descending order.

Hints

Build dict with a for-loop; sort by value to get top-3.

Count Word Frequency and Print Top Three Words

Using only basic Python (no imports, no Counter), write a function that receives a list of word strings and returns a dictionary mapping each unique word to the number of times it appears. As a side effect, print the three most frequent words in descending order of frequency (one per line, as word count).

The function's RETURN VALUE is the frequency dictionary; that is what is graded. Build the dictionary with a simple for-loop, then sort the items by count to find the top three.

Example:

  Input:  ["apple", "banana", "apple", "cherry", "banana", "apple"]
  Returns: {"apple": 3, "banana": 2, "cherry": 1}

Prints: apple 3 banana 2 cherry 1

Constraints

  • Use only basic Python — no collections.Counter, no external libraries.
  • Words are compared exactly as given (case-sensitive, no normalization).
  • The list may be empty, in which case return an empty dict.
  • If there are fewer than three unique words, print only the words that exist.
  • The returned dictionary maps every unique word to its exact count.

Hints

  1. Initialize an empty dict and loop over the words: if the word is already a key, increment its value; otherwise set it to 1.
  2. Use sorted(freq.items(), key=lambda kv: kv[1], reverse=True) to order the words by frequency from highest to lowest.
  3. Slice the sorted list with [:3] to take only the top three, then print each word count pair.