Data Visualization: Count values into bins

The first step of every histogram: count how many values fall in each bin.

What to build

A program that counts values into half-open bins of a given width.

Requirements

  • Bin k is [start + k × width, start + (k + 1) × width). Print [LO, HI): COUNT for every bin from k = 0 to the last bin that holds a value, LO and HI written with Python's :g format.
  • Values below the start are not counted in any bin; if there are any, print below start: N at the end.

Input

Line 1: start and width. Line 2: the values separated by spaces.

Output

One line per bin, and possibly the below-start line.

Constraints

width > 0; 1 to 1000 values; at least one value is at or above the start.

Example

Input:

0 10
3 7 12 15 18 31

Output:

[0, 10): 2
[10, 20): 3
[20, 30): 0
[30, 40): 1

Why it works

With half-open intervals every value falls in exactly one bin, and printing the empty bins keeps the gaps visible, which is part of the shape.

Examples

Example 1 · Input
0 10
3 7 12 15 18 31
Expected output
[0, 10): 2
[10, 20): 3
[20, 30): 0
[30, 40): 1
Example 2 · Input
5 5
5 9.9 10 2
Expected output
[5, 10): 2
[10, 15): 1
below start: 1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

math.floor((v − start) / width) gives the bin number, also for decimals.

Hint 2

Print every bin from 0 to the last non-empty one, including empty bins.

Solution

Show one correct solution (try it yourself first)
import math

start, width = map(float, input().split())
values = [float(v) for v in input().split()]
counts = {}
below = 0
for v in values:
    if v < start:
        below += 1
        continue
    k = math.floor((v - start) / width)
    counts[k] = counts.get(k, 0) + 1
for k in range(max(counts) + 1):
    lo = start + k * width
    print(f"[{lo:g}, {lo + width:g}): {counts.get(k, 0)}")
if below:
    print(f"below start: {below}")

Lesson: Histograms and binning →