Value Count

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Tata Consultancy Services

Problem

A column pulled from an event log may be empty or may never contain the value being searched for, and either way the answer is 0. Otherwise, return how many entries in items equal target.

How many of each? Count them.

Example 1

Input:

items = [1,2,3,2,1,2], target = 2

Output:

3

Example 2

Input:

items = [1,1,1], target = 1

Output:

3

Worked solution and explanation

What this is really asking

This is a multiplicity question wearing the costume of a lookup. Anyone can tell you whether target is in items; the graded cases ask how many times. Reach for target in items or items.index(target) and you return 1 where the answer is 3. Worse, .index() raises ValueError on the empty and no-match batches that should simply come back 0. The whole skill is one full pass where every equal entry adds to the tally.

Step 1: Start the tally at 0

Zero is not a placeholder here. It is the real answer for an empty column and for a batch where target never shows up, so initialising before the scan means neither edge needs its own branch.

Step 2: Visit every entry, never stop early

A return or break on the first hit is the membership trap again. Each entry equal to target adds 1, so [1, 2, 3, 2, 1, 2] with target 2 lands on 3, not 1.

Step 3: Compare with ==, not is

Equality is what the column means. Two 'cat' strings read from different log lines can be different objects, and integers outside the small cached range are not shared, so is can say no to two equal values.

Full pass with an equality check
def count_occur(items: list, target) -> int:
    count = 0
    for item in items:
        if item == target:
            count += 1
    return count
Presence check
return 1 if target in items else 0 stops at the first hit, so three matches collapse to 1. Swapping in items.index(target) also crashes on an empty or no-match batch.
Counting every match
A full pass that adds 1 per equal entry returns 3 for three matches. It also leaves the initial 0 untouched when nothing matches or items is empty.

Common follow-up questions