|
| 1 | +""" |
| 2 | +The diamond kata takes as its input a letter, and outputs it in |
| 3 | +a diamond shape. Given a letter, it prints a diamond starting |
| 4 | +with 'A', with the supplied letter at the widest point. |
| 5 | +""" |
| 6 | + |
| 7 | +import string |
| 8 | + |
| 9 | +CHARS: str = string.ascii_uppercase |
| 10 | + |
| 11 | + |
| 12 | +def rows(letter: str) -> list[str]: |
| 13 | + """ |
| 14 | + Return the diamond rows from 'A' to ``letter``. |
| 15 | +
|
| 16 | + Builds the upper half and mirrors it to form a symmetric diamond. |
| 17 | +
|
| 18 | + :param str letter: Uppercase letter (``'A'``-``'Z'``) marking the widest row. |
| 19 | + :returns: The full diamond as a list of strings, one per row. |
| 20 | + :rtype: list |
| 21 | + :raises ValueError: If ``letter`` is not an ASCII uppercase character. |
| 22 | + """ |
| 23 | + result: list = [] |
| 24 | + letter_index: int = CHARS.index(letter) |
| 25 | + row_length: int = (letter_index * 2) + 1 |
| 26 | + |
| 27 | + for i, char in enumerate(CHARS[: letter_index + 1]): |
| 28 | + # All rows have as many trailing spaces as leading spaces. |
| 29 | + spaces_length: int = letter_index - i |
| 30 | + spaces: str = " " * spaces_length |
| 31 | + # The first/last row contains one 'A'. |
| 32 | + if char == "A": |
| 33 | + result.append(spaces + char + spaces) |
| 34 | + else: |
| 35 | + middle: str = " " * (row_length - 2 - (spaces_length * 2)) |
| 36 | + # All rows, except the first and last, |
| 37 | + # have exactly two identical letters. |
| 38 | + result.append(spaces + char + middle + char + spaces) |
| 39 | + # Mirror the list: the bottom half has the letters in descending order. |
| 40 | + result = result + result[::-1][1:] |
| 41 | + return result |
0 commit comments