Drill

ProblemsPython › inventory

Group stock by how soon it expires

mediuminventoryPython

A food depot dashboard puts every batch into one of four buckets so staff can see what to move first.

expiry_buckets(days_left: list<int>) → map<string, int>

Solve it in the editor →

Where you start

def expiry_buckets(days_left: list[int]) -> dict[str, int]:
    

Worked examples

CallResult
expiry_buckets([-1, 0, 7, 8, 30, 31, 400]){"expired": 1, "week": 2, "month": 2, "later": 2}
expiry_buckets([]){"expired": 0, "week": 0, "month": 0, "later": 0}
expiry_buckets([-5, -5, -5]){"expired": 3, "week": 0, "month": 0, "later": 0}
expiry_buckets([0]){"expired": 0, "week": 1, "month": 0, "later": 0}

Hint

Seed the map with all four keys at zero first, then walk the list once.

Reference solution in Python
def expiry_buckets(days_left: list[int]) -> dict[str, int]:
    out = {'expired': 0, 'week': 0, 'month': 0, 'later': 0}
    for d in days_left:
        if d < 0:
            out['expired'] += 1
        elif d <= 7:
            out['week'] += 1
        elif d <= 30:
            out['month'] += 1
        else:
            out['later'] += 1
    return out

The same problem in another language

More inventory problems in Python