{"record":{"id":"f1c1e64489e9ba72","repo":"TheAlgorithms/Python","slug":"number-of-eigenvectors-must-be-between-1-and-the-n","errorCode":null,"errorMessage":"Number of eigenvectors must be between 1 and the number of nodes in the graph.","messagePattern":"Number of eigenvectors must be between 1 and the number of nodes in the graph\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"graphs/lanczos_eigenvectors.py","lineNumber":100,"sourceCode":"    Returns:\n        A tuple containing:\n            - tridiagonal_matrix: A (num_eigenvectors x num_eigenvectors) symmetric\n                                  matrix.\n            - orthonormal_basis: A (num_nodes x num_eigenvectors) matrix of orthonormal\n                                 basis vectors.\n\n    Raises:\n        ValueError: If num_eigenvectors is less than 1 or greater than the number of\n                    nodes.\n\n    >>> graph = [[1, 2], [0, 2], [0, 1]]\n    >>> T, Q = lanczos_iteration(graph, 2)\n    >>> T.shape == (2, 2) and Q.shape == (3, 2)\n    True\n    \"\"\"\n    num_nodes: int = len(graph)\n    if not (1 <= num_eigenvectors <= num_nodes):\n        raise ValueError(\n            \"Number of eigenvectors must be between 1 and the number of \"\n            \"nodes in the graph.\"\n        )\n\n    orthonormal_basis: np.ndarray = np.zeros((num_nodes, num_eigenvectors))\n    tridiagonal_matrix: np.ndarray = np.zeros((num_eigenvectors, num_eigenvectors))\n\n    rng = np.random.default_rng()\n    initial_vector: np.ndarray = rng.random(num_nodes)\n    initial_vector /= np.sqrt(np.dot(initial_vector, initial_vector))\n    orthonormal_basis[:, 0] = initial_vector\n\n    prev_beta: float = 0.0\n    for iter_index in range(num_eigenvectors):\n        result_vector: np.ndarray = multiply_matrix_vector(\n            graph, orthonormal_basis[:, iter_index]\n        )\n        if iter_index > 0:","sourceCodeStart":82,"sourceCodeEnd":118,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/graphs/lanczos_eigenvectors.py#L82-L118","documentation":"Raised by lanczos_iteration in graphs/lanczos_eigenvectors.py when num_eigenvectors is outside [1, num_nodes]. The Lanczos process builds an orthonormal basis of exactly that many vectors, so zero or negative counts are meaningless and counts exceeding the node count would exceed the dimension of the space (the Krylov subspace can never have more than n independent vectors).","triggerScenarios":"Calling lanczos_iteration(graph, 0) or with a negative k; requesting k > len(graph), e.g. 5 eigenvectors from a 3-node graph; computing k as a fraction of node count that rounds to 0 for tiny graphs (e.g. int(0.1 * 2) == 0).","commonSituations":"Parameterized routines where k is derived from graph size and floors to 0 on small inputs; user-facing APIs exposing 'number of components' without bounds; defaults tuned for large graphs applied to toy examples.","solutions":["Clamp k into range: `k = max(1, min(k, len(graph)))`.","Validate input early and raise a clear error to your own callers when the request cannot be honored.","When k is derived (e.g. percentage of nodes), ensure the formula returns at least 1 for the smallest graph you support."],"exampleFix":"# before\nk = int(0.1 * len(graph))\nT, Q = lanczos_iteration(graph, k)  # k == 0 for small graphs\n\n# after\nk = max(1, min(int(0.1 * len(graph)) or 1, len(graph)))\nT, Q = lanczos_iteration(graph, k)","handlingStrategy":"validation","validationCode":"k = max(1, min(num_eigenvectors, len(graph)))","typeGuard":"def valid_k(k: int, num_nodes: int) -> bool:\n    return 1 <= k <= num_nodes","tryCatchPattern":null,"preventionTips":["Clamp derived k values: max(1, min(k, len(graph))).","Validate user-supplied component counts against graph size in your own API.","Percentage-based k formulas must round up, never down to 0."],"tags":["graph","lanczos","eigenvectors","parameter-validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}