py_list_intersection_finder
Código comentado línea a línea y paso a paso:
Entregas: py_list_intersection_finder.py con list_intersection_finder(lists). Rank 04 · nivel 2.
Qué pide (en palabras normales)
- Elementos que están en todas las listas, sin repetir, ordenados. Entrada vacía o alguna lista vacía →
[].
Subject (enunciado original)
Write a function that finds the intersection of multiple sorted lists.
Return a new list containing elements that appear in ALL input lists, in sorted order.
The function should:
- Return elements that appear in ALL lists
- Result should be sorted in ascending order
- Remove duplicates from the result
- Handle empty input or empty lists gracefully
- If any list is empty, the intersection is empty
Expected file: py_list_intersection_finder.py
Function signature:
def list_intersection_finder(lists: list[list[int]]) -> list[int]:
Examples:
list_intersection_finder([[1, 2, 3], [2, 3, 4], [2, 3, 5]])
=> [2, 3]
list_intersection_finder([[1, 2, 3, 4], [2, 4, 6, 8], [4, 8, 12]])
=> [4]
list_intersection_finder([[1, 1, 2, 3], [1, 2, 2, 3], [1, 2, 3, 3]])
=> [1, 2, 3]
list_intersection_finder([[1, 2, 3], [4, 5, 6]])
=> []
list_intersection_finder([])
=> []
list_intersection_finder([[1, 2, 3], []])
=> []
list_intersection_finder([[5]])
=> [5]
Solución: sets
if not lists:
return []
common = set(lists[0])
for other in lists[1:]:
common &= set(other)
return sorted(common)
Intersección de conjuntos encadenada. Que las listas vengan ordenadas no hace falta aprovecharlo: con sets es lineal igual y mucho más corto que la versión de punteros múltiples.
Trampas
set.intersection(*map(set, lists))también vale en una línea, pero conlists == []lanzaTypeError. Elifsigue haciendo falta.- Devuelve
sorted(...), que es unalist.list(common)sin ordenar sale en orden arbitrario.