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
Given items, a column of values pulled from an event log, and a target value, return how many entries in items equal target. The values can be numbers or strings.
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. 2 '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 2 equal values.
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 0stops at the first hit, so 3 matches collapse to 1. Swapping initems.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 3 matches. It also leaves the initial 0 untouched when nothing matches or
itemsis empty.
Common follow-up questions
- What if `items` were sorted? (Tests bisecting for the first and last occurrence to count in O(log n).)
- What if the values were float sensor readings? (Tests matching within a tolerance such as `abs(item - target) < epsilon` instead of exact equality.)
- How does your loop compare to `items.count(target)`? (Tests knowing both do the same O(n) work, with the built-in running in C.)
- What if you needed the count of every value, not just one? (Tests building one frequency map in a single pass instead of a separate scan per value.)