The Price Bander

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
L4
Asked in
Gemini

Problem

A catalog service segments products into price brackets before it renders them. Given prices, a dict mapping product names to prices, return a new dict mapping each name to its bracket: 'low' for anything under 10, 'mid' for anything under 50, and 'high' otherwise.

Different prices, different treatment.

Example

Input:

prices = {"pen":2,"book":15,"apple":1.5,"laptop":999}

Output:

{"pen":"low","book":"mid","apple":"low","laptop":"high"}

Worked solution and explanation

It looks like labeling, it is really about overlap

Strip the catalog costume and this is a nested-band classification: the bands overlap, because every price under 10 is also under 50. So the answer to 'which band?' depends entirely on which comparison you reach first. Anyone can write three if branches. The candidates who fail are the ones who reach for the widest condition first, or reach for <= at a cutoff. Reverse the order and every cheap item comes back tagged 'mid'; slip one <= and a price of exactly 10 lands in 'low'. Nothing throws an error, the numbers just come out quietly wrong.


Walking to the answer

Step 1: Scan each product and its price

Iterate the name/price pairs. Nothing here needs the values sorted or the keys touched, so a straight pass over the dict is enough.

Step 2: Resolve the band in order

Run the cutoffs from tightest to loosest: price < 10 is 'low', then price < 50 is 'mid', otherwise 'high'. The elif chain guarantees the first matching band wins, which is exactly what the overlap demands.

Step 3: Emit a new dict

Write name -> band into a fresh dict and return it. Don't mutate the input; the graders reuse it.


The solution

Ordered threshold classification
def price_tiers(prices):
    tiers = {}
    for name, price in prices.items():
        if price < 10:
            tiers[name] = 'low'
        elif price < 50:
            tiers[name] = 'mid'
        else:
            tiers[name] = 'high'
    return tiers

Common follow-up questions