Let a rule choose the number of bins, then draw the histogram.
What to build
A program that bins data with Sturges' rule and draws the histogram.
Requirements
- k = ceil(log2 n) + 1 bins of width (max − min) / k, starting at the minimum. Bins are half-open except the last, which also holds the maximum.
- Print
k = K, width = Wwith W to two decimals, then for each binLO - HI | BAR COUNT, with LO and HI to two decimals and BAR the count's number of#.
Input
One line of numbers separated by spaces.
Output
k + 1 lines.
Constraints
2 to 1000 values, not all equal.
Example
Input:
1 2 3 4 5 6 7 8
Output:
k = 4, width = 1.75
1.00 - 2.75 | ## 2
2.75 - 4.50 | ## 2
4.50 - 6.25 | ## 2
6.25 - 8.00 | ## 2
Why it works
Sturges' rule grows the number of bins slowly with the amount of data, and closing the last bin makes sure the largest value is counted.
Examples
Example 1 · Input
1 2 3 4 5 6 7 8
Expected output
k = 4, width = 1.75 1.00 - 2.75 | ## 2 2.75 - 4.50 | ## 2 4.50 - 6.25 | ## 2 6.25 - 8.00 | ## 2
Example 2 · Input
2 2 2 9
Expected output
k = 3, width = 2.33 2.00 - 4.33 | ### 3 4.33 - 6.67 | 0 6.67 - 9.00 | # 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
k = math.ceil(math.log2(n)) + 1 and width = (max − min) / k.
Hint 2
The bin index is int((v − min) / width), but the maximum belongs to the last bin.
Solution
Show one correct solution (try it yourself first)
import math
values = [float(v) for v in input().split()]
n = len(values)
lo, hi = min(values), max(values)
k = math.ceil(math.log2(n)) + 1
width = (hi - lo) / k
counts = [0] * k
for v in values:
counts[min(int((v - lo) / width), k - 1)] += 1
print(f"k = {k}, width = {width:.2f}")
for i, c in enumerate(counts):
a = lo + i * width
print(f"{a:.2f} - {a + width:.2f} | {'#' * c} {c}")