Back
+35 XP
Concept

Module 39 Capstone: Markdown Table Generator & Validator

Documentation pipelines automatically transform structured database records into readable Markdown tables. The generator computes maximum column widths, pads cells with spaces, respects text alignment markers (colon-dash separators), and validates column row lengths dynamically 📊📑🏆.

python
def render_simple_table(headers, rows):
    widths = [max(len(str(h)), max(len(str(r[i])) for r in rows)) for i, h in enumerate(headers)]
    fmt = "| " + " | ".join(f"{{:<{w}}}" for w in widths) + " |"
    sep = "| " + " | ".join("-" * w for w in widths) + " |"
    return "\n".join([fmt.format(*headers), sep] + [fmt.format(*r) for r in rows])

print(render_simple_table(["User", "Status"], [["Alice", "ACTIVE"], ["Bob", "IDLE"]]))

# 15. Module 39 Capstone: Markdown Table Generator & Validator Manually calculating spaces and dashes to create ASCII tables in documentation or terminal outputs is tedious and error-prone. A programmatic Markdown table generator formats dynamic analytics rows with mathematical precision 🛑. ```text | Name | Role | Salary | | ----- | ----------- | -------: | | Alice | Architect | $180,000 | | Bob | DevOps Lead | $165,000 | ``` ### Generator Architecture 1. **Dynamic Column Sizing**: Iterate over both header labels and all row values to determine the exact maximum length needed for each column: $$W_j = \max\left(\operatorname{len}(\text{header}_j), \max_{i} \operatorname{len}(\text{row}_{i, j})\right)$$ 2. **Alignment Formatter**: - `left`: `s.ljust(w)` + `-------` - `right`: `s.rjust(w)` + `------:` - `center`: `s.center(w)` + `:-----:` 3. **Structured Padding**: Surround every cell with clean boundary spaces (`| cell |`) so markdown parsers render without edge defects 📊📑🏆. --- ### Interactive Pop-Quiz 🧠 #### How does GitHub Flavored Markdown distinguish between left, right, and center aligned table columns? - [ ] By placing colons in the separator row: `:---` for left, `---:` for right, and `:---:` for center alignment 📊 - [ ] By writing CSS inline styles inside the pipe symbols - [ ] By encoding column headers in Base64 - [ ] By using double pipes `||` for right-aligned text --- ### Practical Challenge 🎯 Implement `generate_markdown_table(headers: list[str], rows: list[list[str]], alignments: list[str] = None) -> str`. Calculate dynamic column widths matching the longest cell in each column. Format headers, separator row (`---:` for right, `-----` for left), and data rows with trailing pipes `|`. Test with headers `['Name', 'Role', 'Salary']`, rows `[['Alice', 'Architect', '$180,000'], ['Bob', 'DevOps Lead', '$165,000']]`, and alignments `['left', 'left', 'right']`. Assert formatted lines and print table. <details> <summary>Solution</summary> ```python def generate_markdown_table(headers: list[str], rows: list[list[str]], alignments: list[str] = None) -> str: col_count = len(headers) widths = [len(h) for h in headers] for row in rows: for j, cell in enumerate(row): widths[j] = max(widths[j], len(str(cell))) def format_row(cells): parts = [] for j, cell in enumerate(cells): w = widths[j] align = alignments[j] if alignments and j < len(alignments) else "left" s = str(cell) if align == "right": parts.append(s.rjust(w)) elif align == "center": parts.append(s.center(w)) else: parts.append(s.ljust(w)) return "| " + " | ".join(parts) + " |" sep_parts = [] for j in range(col_count): w = widths[j] align = alignments[j] if alignments and j < len(alignments) else "left" if align == "right": sep_parts.append("-" * (w - 1) + ":") elif align == "center": sep_parts.append(":" + "-" * max(1, w - 2) + ":") else: sep_parts.append("-" * w) sep_line = "| " + " | ".join(sep_parts) + " |" lines = [format_row(headers), sep_line] for row in rows: lines.append(format_row(row)) return "\n".join(lines) headers = ["Name", "Role", "Salary"] rows = [ ["Alice", "Architect", "$180,000"], ["Bob", "DevOps Lead", "$165,000"] ] table = generate_markdown_table(headers, rows, ["left", "left", "right"]) assert "| Name | Role | Salary |" in table assert "| Alice | Architect | $180,000 |" in table assert "| Bob | DevOps Lead | $165,000 |" in table print(f"Generated Markdown Table:\n{table}") ``` </details>

Checkpoint

How does GitHub Flavored Markdown distinguish between left, right, and center aligned table columns? 🧠

Practice

Implement `generate_markdown_table(headers: list[str], rows: list[list[str]], alignments: list[str] = None) -> str`. Calculate dynamic column widths matching the longest cell in each column. Format headers, separator row with right-align colons or default dashes, and data rows with trailing pipes `|`. Test with headers `['Name', 'Role', 'Salary']`, rows `[['Alice', 'Architect', '$180,000'], ['Bob', 'DevOps Lead', '$165,000']]`, and alignments `['left', 'left', 'right']`. Assert formatted lines and print table. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks