Real charts have a fixed width, so bars are scaled to it, and ranking charts are sorted.
What to build
A program that prints a sorted bar chart scaled to a given width.
Requirements
- Sort the categories by value from largest to smallest, equal values in alphabetical order of label.
- Each bar has int(value / largest × W + 0.5)
#characters. PrintLABEL | BAR VALUEwith LABEL left-aligned to the longest label's length.
Input
Line 1: W. Line 2: n. Then n lines LABEL VALUE with whole-number values.
Output
n lines.
Constraints
1 ≤ W ≤ 60; 1 ≤ n ≤ 30; values are 0 or more and the largest is more than 0.
Example
Input:
20
5
North 42
South 18
East 35
West 27
Central 9
Output:
North | #################### 42
East | ################# 35
West | ############# 27
South | ######### 18
Central | #### 9
Why it works
Scaling by the largest value keeps every bar inside the width while keeping lengths proportional, and rounding half up makes the result the same on every run and every computer.
Examples
Example 1 · Input
20 5 North 42 South 18 East 35 West 27 Central 9
Expected output
North | #################### 42 East | ################# 35 West | ############# 27 South | ######### 18 Central | #### 9
Example 2 · Input
10 3 b 5 a 5 c 1
Expected output
a | ########## 5 b | ########## 5 c | ## 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Sort with the key (-value, label) for largest first and ties in alphabetical order.
Hint 2
Round half up: int(value / largest * width + 0.5).
Solution
Show one correct solution (try it yourself first)
w = int(input())
n = int(input())
rows = []
for _ in range(n):
label, value = input().split()
rows.append((label, int(value)))
rows.sort(key=lambda r: (-r[1], r[0]))
largest = rows[0][1]
lw = max(len(label) for label, _ in rows)
for label, value in rows:
length = int(value / largest * w + 0.5)
print(f"{label:<{lw}} | {'#' * length} {value}")