A histogram shows the shape of a column at a glance. Draw one in text, including the empty bins, so that gaps stay visible.
What to build
A program that counts values in equal-width bins and prints a text histogram.
Requirements
- Bins start at multiples of the width. Print every bin from the one holding the smallest value to the one holding the largest, in order.
- Print each bin as
L-U: Cfollowed by a space and C#characters, where U = L + width − 1; for an empty bin print justL-U: 0.
Input
Line 1: the bin width. Line 2: the values, whole numbers separated by spaces.
Output
One line per bin.
Constraints
1 ≤ width ≤ 1000; 1 to 1000 values between 0 and 100000.
Example
Input:
10
23 35 31 47 52 29 38
Output:
20-29: 2 ##
30-39: 3 ###
40-49: 1 #
50-59: 1 #
Why it works
Integer division by the width maps every value to the start of its bin, and looping over all starts between the smallest and largest bin prints the empty ones as well.
Examples
10 23 35 31 47 52 29 38
20-29: 2 ## 30-39: 3 ### 40-49: 1 # 50-59: 1 #
5 1 2 3 14
0-4: 3 ### 5-9: 0 10-14: 1 #
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The start of a value's bin is value // width * width.
Hint 2
Loop from the first bin's start to the last bin's start in steps of width, so that empty bins are printed too.
Solution
Show one correct solution (try it yourself first)
width = int(input())
values = list(map(int, input().split()))
counts = {}
for v in values:
start = v // width * width
counts[start] = counts.get(start, 0) + 1
first = min(values) // width * width
last = max(values) // width * width
for start in range(first, last + 1, width):
c = counts.get(start, 0)
line = f"{start}-{start + width - 1}: {c}"
if c:
line += " " + "#" * c
print(line)