Problem 142270 · easy · Level 01 Prerequisites & Setup

Counting Into Equal Bins

frequency tables · bins · histograms · integer division

A histogram groups measurements into bins of equal width. Bin 0 covers the values from start up to (but not including) start + width, bin 1 the next width, and so on up to bin bins - 1. A value exactly on a boundary belongs to the bin that starts there.

Write bin_counts(values, start, width, bins) that returns a list of bins counts: how many values fall into each bin. Values below start, or at or beyond the end of the last bin, are left out of the table.

Examples

Input:  values = [3, -2, 7, 12, 5, -8, 0, 4], start = -10, width = 5, bins = 5
Output: [1, 1, 3, 2, 1]
Explanation: the bins are [-10, -5), [-5, 0), [0, 5), [5, 10), [10, 15);
-8 | -2 | 0, 3, 4 | 5, 7 | 12.

Input:  values = [1.5, 2.0, 9.9, 10.0, -0.1], start = 0, width = 2.5, bins = 4
Output: [2, 0, 0, 1]
Explanation: 10.0 is the end of the last bin, and -0.1 is below the start; both are left out.

Constraints

  • 0 <= len(values) <= 10**5, values are ints or floats between -10**6 and 10**6
  • start is a number, width > 0, and 1 <= bins <= 1000
  • the tests use widths and values for which the bin arithmetic is exact

Goals

  • Put each value into exactly one equal-width bin
  • Compute the bin number arithmetically instead of testing every bin
  • Keep empty bins in the table
Starting Python…