MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / validate_adjacency_list

Function validate_adjacency_list

graphs/lanczos_eigenvectors.py:32–68  ·  view source on GitHub ↗

Validates the adjacency list format for the graph. Args: graph: A list of lists where each sublist contains the neighbors of a node. Raises: ValueError: If the graph is not a list of lists, or if any node has invalid neighbors (e.g., out-of-range or non-

(graph: list[list[int | None]])

Source from the content-addressed store, hash-verified

30
31
32def validate_adjacency_list(graph: list[list[int | None]]) -> None:
33 """Validates the adjacency list format for the graph.
34
35 Args:
36 graph: A list of lists where each sublist contains the neighbors of a node.
37
38 Raises:
39 ValueError: If the graph is not a list of lists, or if any node has
40 invalid neighbors (e.g., out-of-range or non-integer values).
41
42 >>> validate_adjacency_list([[1, 2], [0], [0, 1]])
43 >>> validate_adjacency_list([[]]) # No neighbors, valid case
44 >>> validate_adjacency_list([[1], [2], [-1]]) # Invalid neighbor
45 Traceback (most recent call last):
46 ...
47 ValueError: Invalid neighbor -1 in node 2 adjacency list.
48 """
49 if not isinstance(graph, list):
50 raise ValueError("Graph should be a list of lists.")
51
52 for node_index, neighbors in enumerate(graph):
53 if not isinstance(neighbors, list):
54 no_neighbors_message: str = (
55 f"Node {node_index} should have a list of neighbors."
56 )
57 raise ValueError(no_neighbors_message)
58 for neighbor_index in neighbors:
59 if (
60 not isinstance(neighbor_index, int)
61 or neighbor_index < 0
62 or neighbor_index >= len(graph)
63 ):
64 invalid_neighbor_message: str = (
65 f"Invalid neighbor {neighbor_index} in node {node_index} "
66 f"adjacency list."
67 )
68 raise ValueError(invalid_neighbor_message)
69
70
71def lanczos_iteration(

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected