Generate the rect elements of a bar chart, the way a chart library would.
What to build
A program that writes SVG rect elements for a bar chart.
Requirements
- With n values, each bar's slot is W ÷ n wide. Bar i (from 0) has x = i × W ÷ n + 1, width = W ÷ n − 2, height = value ÷ max × H and y = H − height.
- Print one line per bar:
<rect x="X" y="Y" width="WIDTH" height="HEIGHT"/>, with every number in:gformat.
Input
Line 1: W and H. Line 2: the values.
Output
One line per value.
Constraints
1 to 50 values, all 0 or more, with a maximum over 0; W ÷ n is over 2.
Example
Input:
100 50
10 5
Output:
<rect x="1" y="0" width="48" height="50"/>
<rect x="51" y="25" width="48" height="25"/>
Why it works
Bars share a baseline at the bottom of the drawing, so each rectangle's top edge is the baseline minus its height, and equal slots with a fixed inset keep the bars evenly spaced.
Examples
Example 1 · Input
100 50 10 5
Expected output
<rect x="1" y="0" width="48" height="50"/> <rect x="51" y="25" width="48" height="25"/>
Example 2 · Input
30 10 1
Expected output
<rect x="1" y="0" width="28" height="10"/>
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Each bar has a slot of width W ÷ n; the bar is 2 narrower and starts 1 unit into its slot.
Hint 2
The height is value ÷ max × H, and y = H − height.
Solution
Show one correct solution (try it yourself first)
w, h = map(float, input().split())
values = [float(v) for v in input().split()]
slot = w / len(values)
top = max(values)
for i, v in enumerate(values):
bh = v / top * h
print(f'<rect x="{i * slot + 1:g}" y="{h - bh:g}" width="{slot - 2:g}" height="{bh:g}"/>')