{"record":{"id":"d3dc0bd0e3af28ef","repo":"TheAlgorithms/Python","slug":"vector-length-must-match-the-number-of-nodes-in-th","errorCode":null,"errorMessage":"Vector length must match the number of nodes in the graph.","messagePattern":"Vector length must match the number of nodes in the graph\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"graphs/lanczos_eigenvectors.py","lineNumber":156,"sourceCode":"    Args:\n        graph: The adjacency list of the graph.\n        vector: A 1D numpy array representing the vector to multiply.\n\n    Returns:\n        A numpy array representing the product of the adjacency list and the vector.\n\n    Raises:\n        ValueError: If the vector's length does not match the number of nodes in the\n                    graph.\n\n    >>> multiply_matrix_vector([[1, 2], [0, 2], [0, 1]], np.array([1, 1, 1]))\n    array([2., 2., 2.])\n    >>> multiply_matrix_vector([[1, 2], [0, 2], [0, 1]], np.array([0, 1, 0]))\n    array([1., 0., 1.])\n    \"\"\"\n    num_nodes: int = len(graph)\n    if vector.shape[0] != num_nodes:\n        raise ValueError(\"Vector length must match the number of nodes in the graph.\")\n\n    result: np.ndarray = np.zeros(num_nodes)\n    for node_index, neighbors in enumerate(graph):\n        for neighbor_index in neighbors:\n            result[node_index] += vector[neighbor_index]\n    return result\n\n\ndef find_lanczos_eigenvectors(\n    graph: list[list[int | None]], num_eigenvectors: int\n) -> tuple[np.ndarray, np.ndarray]:\n    \"\"\"Computes the largest eigenvalues and their corresponding eigenvectors using the\n    Lanczos method.\n\n    Args:\n        graph: The graph as a list of adjacency lists.\n        num_eigenvectors: Number of largest eigenvalues and eigenvectors to compute.\n","sourceCodeStart":138,"sourceCodeEnd":174,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/graphs/lanczos_eigenvectors.py#L138-L174","documentation":"Thrown by multiply_matrix_vector() in the Lanczos eigenvector computation. The graph is given as an adjacency list (list of neighbor lists), so len(graph) is the node count, and the vector passed in must have exactly that many entries (vector.shape[0] == num_nodes). Any mismatch between vector dimension and graph size aborts the matrix-vector product before it starts.","triggerScenarios":"Calling multiply_matrix_vector(graph, vector) where vector was built from a different graph or with a hardcoded size, e.g. passing np.array([1, 1]) with a 3-node graph [[1,2],[0,2],[0,1]]. Also happens when the start vector for Lanczos is created with len(graph[0]) or number-of-edges instead of number-of-nodes.","commonSituations":"Reusing an eigenvector/starting vector from a previous graph run, off-by-one when constructing the initial vector, or mixing a degree-array length with the node count after graph mutation (nodes added/removed between building the vector and calling the routine).","solutions":["Construct the vector with exactly len(graph) entries, e.g. np.ones(len(graph)) or the normalized all-ones start vector used by find_lanczos_eigenvectors.","Rebuild the vector whenever the graph changes; do not cache vectors across graph modifications.","Add an assert len(vector) == len(graph) before the call in your own code to fail with your own context."],"exampleFix":"# before\nvector = np.ones(len(graph[0]))  # wrong: neighbors of first node\nmultiply_matrix_vector(graph, vector)\n\n# after\nvector = np.full(len(graph), 1.0) / np.sqrt(len(graph))\nmultiply_matrix_vector(graph, vector)","handlingStrategy":"validation","validationCode":"n = len(graph)\nassert vector.shape[0] == n, f\"vector has {vector.shape[0]} entries, graph has {n} nodes\"","typeGuard":"def is_compatible(graph: list[list[int]], vector: np.ndarray) -> bool:\n    return isinstance(vector, np.ndarray) and vector.ndim == 1 and vector.shape[0] == len(graph)","tryCatchPattern":"try:\n    y = multiply_matrix_vector(graph, vector)\nexcept ValueError as e:\n    raise ValueError(f\"graph/vector mismatch for graph of {len(graph)} nodes: {e}\") from e","preventionTips":["Always construct the start vector as np.full(len(graph), value).","Rebuild vectors after any change to the graph's node set.","Keep one authoritative node count variable and derive both graph and vector from it."],"tags":["graph","numpy","validation","lanczos","eigenvectors"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}