py_constellation_mapper
Código comentado línea a línea y paso a paso:
Entregas: py_constellation_mapper.py con constellation_mapper(stars, dim). Rank 04 · nivel 1.
Qué pide (en palabras normales)
- Pintar estrellas
(fila, columna)en una rejilladim × dimde puntos. Devuelve una lista de strings, una por fila. - Coordenadas fuera: ignorar. Repetidas: una sola estrella.
Subject (enunciado original)
Write a function that maps a constellation of stars onto a grid and returns the visual representation as a list of strings.
The function should:
- Take a list of star coordinates as tuples (row, col) and grid size as integer
- Return a list of strings representing the grid
- Stars are represented by '*' and empty spaces by '.'
- Grid coordinates start from (0, 0) at top-left
- Ignore coordinates outside the grid boundaries
- Handle duplicate coordinates (star appears only once)
Expected file: py_constellation_mapper.py
Function signature:
def constellation_mapper(stars: list[tuple[int, int]], dim: int) -> list[str]:
Examples:
constellation_mapper([(0, 0), (1, 1), (2, 2)], 3)
=> ['*..', '.*.', '..*']
constellation_mapper([(1, 1), (0, 1), (2, 1), (1, 0), (1, 2)], 3)
=> ['.*.', '***', '.*.']
constellation_mapper([], 2)
=> ['..', '..']
constellation_mapper([(0, 0), (0, 0), (1, 1)], 2)
=> ['*.', '.*']
constellation_mapper([(0, 0), (5, 5)], 3)
=> ['*..', '...', '...']
constellation_mapper([(1, 0), (1, 1), (1, 2)], 3)
=> ['...', '***', '...']
Solución
grid = [["."] * dim for _ in range(dim)]
for row, col in stars:
if 0 <= row < dim and 0 <= col < dim:
grid[row][col] = "*"
return ["".join(line) for line in grid]
Rejilla mutable de caracteres, pinto, y al final convierto cada fila a string. Los strings de Python son inmutables, por eso el paso intermedio con listas.
Trampas
[["."] * dim] * dimcrea una fila referenciadadimveces: pintas en una y aparece en todas. La comprensión confor _ in range(dim)crea filas independientes.- Comprueba límites antes de indexar:
grid[-1]no falla, pinta la última fila. - Es
(row, col):grid[row][col]. Al revés sale la rejilla transpuesta y los ejemplos simétricos no te lo avisan.