Data Visualization: Grouped bars for two years

Compare two series category by category with grouped bars on one shared scale, and label the change.

What to build

A program that draws grouped bars for two years and the change between them.

Requirements

  • First print the legend # YEAR1 = YEAR2 (two spaces before =).
  • For each category in input order print two lines: LABEL | BAR V1 with # characters, then the label column filled with spaces and | BAR V2 (CHANGE) with = characters, where CHANGE is the percentage change from V1 to V2 with a sign and one decimal (for example +25.0%), or new when V1 is 0.
  • Bars have int(value / largest × W + 0.5) characters, where largest is the largest value of both years. Labels are left-aligned to the longest label.

Input

Line 1: W. Line 2: YEAR1 YEAR2. Line 3: n. Then n lines LABEL V1 V2.

Output

The legend, then 2n lines.

Constraints

1 ≤ W ≤ 60; 1 ≤ n ≤ 20; whole-number values, at least one more than 0.

Example

Input:

10
2023 2024
2
Tea 40 50
Rice 20 15

Output:

# 2023  = 2024
Tea  | ######## 40
     | ========== 50 (+25.0%)
Rice | #### 20
     | === 15 (-25.0%)

Why it works

One shared scale is what makes bars of different years comparable, and putting each pair next to each other lets the eye compare within a category, which grouped bars are for.

Examples

Example 1 · Input
10
2023 2024
2
Tea 40 50
Rice 20 15
Expected output
# 2023  = 2024
Tea  | ######## 40
     | ========== 50 (+25.0%)
Rice | #### 20
     | === 15 (-25.0%)
Example 2 · Input
6
2020 2021
2
A 0 3
B 6 6
Expected output
# 2020  = 2021
A |  0
  | === 3 (new)
B | ###### 6
  | ====== 6 (+0.0%)

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Use one scale for both series: the largest value of either year.

Hint 2

The change is (new − old) / old × 100, formatted with f"{pct:+.1f}%".

Solution

Show one correct solution (try it yourself first)
w = int(input())
y1, y2 = input().split()
n = int(input())
rows = []
for _ in range(n):
    label, a, b = input().split()
    rows.append((label, int(a), int(b)))
largest = max(max(a, b) for _, a, b in rows)
lw = max(len(label) for label, _, _ in rows)


def bar(value, ch):
    return ch * int(value / largest * w + 0.5)


print(f"# {y1}  = {y2}")
for label, a, b in rows:
    change = "new" if a == 0 else f"{(b - a) / a * 100:+.1f}%"
    print(f"{label:<{lw}} | {bar(a, '#')} {a}")
    print(f"{'':<{lw}} | {bar(b, '=')} {b} ({change})")

Lesson: Bar charts →