np.histogram splits the data's range into equal bins and counts the values in each. Reproduce its counts and edges.
What to build
A program that prints histogram counts and bin edges.
Requirements
- Print
countsfollowed by the counts in NumPy's 1-D format. - Then print
edgesfollowed by the bins + 1 edges, each in Python's:gformat, separated by spaces. - Bins include their left edge; the last bin also includes the maximum. When all values are equal, use the range min − 0.5 to max + 0.5.
Input
Line 1: the data. Line 2: the number of bins.
Output
Two lines.
Constraints
1 to 1000 values between −10⁶ and 10⁶; 1 ≤ bins ≤ 50.
Example
Input:
1 2 2 3 4
3
Output:
counts [1 2 2]
edges 1 2 3 4
Why it works
Equal-width bins make a value's bin a simple division, and closing the last bin keeps the maximum inside the range instead of creating an extra bin for it.
Examples
1 2 2 3 4 3
counts [1 2 2] edges 1 2 3 4
0 10 2
counts [1 1] edges 0 5 10
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
width = (max − min) ÷ bins, and a value's bin is int((x − min) ÷ width).
Hint 2
Put the maximum into the last bin by taking the smaller of that index and bins − 1.
Hint 3
If all values are equal, NumPy uses the range min − 0.5 to max + 0.5.
Solution
Show one correct solution (try it yourself first)
data = [float(x) for x in input().split()]
bins = int(input())
lo, hi = min(data), max(data)
if lo == hi:
lo, hi = lo - 0.5, hi + 0.5
width = (hi - lo) / bins
counts = [0] * bins
for x in data:
counts[min(int((x - lo) / width), bins - 1)] += 1
w = max(len(str(c)) for c in counts)
print("counts [" + " ".join(str(c).rjust(w) for c in counts) + "]")
print("edges", " ".join(f"{lo + i * width:g}" for i in range(bins + 1)))