Quick Overview

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

Count Word Frequency and Print Top Three Words

Company: PayPal

Role: Data Scientist

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Onsite

##### 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.

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

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.

Examples

Input: (["apple", "banana", "apple", "cherry", "banana", "apple"],)

Expected Output: {"apple": 3, "banana": 2, "cherry": 1}

Explanation: apple appears 3 times, banana 2, cherry 1. The dict captures all counts; the top-3 printed are apple, banana, cherry.

Input: (["a", "b", "c", "d"],)

Expected Output: {"a": 1, "b": 1, "c": 1, "d": 1}

Explanation: All four words are unique, each with frequency 1.

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.

Loading coding console...