Bucket some readings
A chart needs counts per band rather than raw readings — how many orders fell between 0 and 9, 10 and 19, and so on.
- Readings are never negative.
- A bucket is named by the value it starts at, written as a string: "0", "10", "20".
- Buckets with nothing in them do not appear.
- A bucket size of zero or less gives an empty result.
histogram(values: list<int>, bucket_size: int) → map<string, int>
Where you start
def histogram(values: list[int], bucket_size: int) -> dict[str, int]:
Worked examples
| Call | Result |
|---|---|
histogram([0, 5, 10, 15, 23], 10) | {"0": 2, "10": 2, "20": 1} |
histogram([9, 10], 10) | {"0": 1, "10": 1} |
histogram([1, 2, 3], 1) | {"1": 1, "2": 1, "3": 1} |
histogram([1, 2], 0) | {} |
Hint
Integer-divide by the bucket size, multiply back, and that is the bucket name.
Reference solution in Python
def histogram(values: list[int], bucket_size: int) -> dict[str, int]:
if bucket_size <= 0:
return {}
result = {}
for v in values:
k = str(v // bucket_size * bucket_size)
result[k] = result.get(k, 0) + 1
return result