TheAlgorithms/Python · error · ValueError

Number of eigenvectors must be between 1 and the number of n

Error message

Number of eigenvectors must be between 1 and the number of nodes in the graph.

What it means

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).

Source

Thrown at graphs/lanczos_eigenvectors.py:100

    Returns:
        A tuple containing:
            - tridiagonal_matrix: A (num_eigenvectors x num_eigenvectors) symmetric
                                  matrix.
            - orthonormal_basis: A (num_nodes x num_eigenvectors) matrix of orthonormal
                                 basis vectors.

    Raises:
        ValueError: If num_eigenvectors is less than 1 or greater than the number of
                    nodes.

    >>> graph = [[1, 2], [0, 2], [0, 1]]
    >>> T, Q = lanczos_iteration(graph, 2)
    >>> T.shape == (2, 2) and Q.shape == (3, 2)
    True
    """
    num_nodes: int = len(graph)
    if not (1 <= num_eigenvectors <= num_nodes):
        raise ValueError(
            "Number of eigenvectors must be between 1 and the number of "
            "nodes in the graph."
        )

    orthonormal_basis: np.ndarray = np.zeros((num_nodes, num_eigenvectors))
    tridiagonal_matrix: np.ndarray = np.zeros((num_eigenvectors, num_eigenvectors))

    rng = np.random.default_rng()
    initial_vector: np.ndarray = rng.random(num_nodes)
    initial_vector /= np.sqrt(np.dot(initial_vector, initial_vector))
    orthonormal_basis[:, 0] = initial_vector

    prev_beta: float = 0.0
    for iter_index in range(num_eigenvectors):
        result_vector: np.ndarray = multiply_matrix_vector(
            graph, orthonormal_basis[:, iter_index]
        )
        if iter_index > 0:

View on GitHub (pinned to f5988cc097)

Solutions

  1. Clamp k into range: `k = max(1, min(k, len(graph)))`.
  2. Validate input early and raise a clear error to your own callers when the request cannot be honored.
  3. When k is derived (e.g. percentage of nodes), ensure the formula returns at least 1 for the smallest graph you support.

Example fix

# before
k = int(0.1 * len(graph))
T, Q = lanczos_iteration(graph, k)  # k == 0 for small graphs

# after
k = max(1, min(int(0.1 * len(graph)) or 1, len(graph)))
T, Q = lanczos_iteration(graph, k)
Defensive patterns

Strategy: validation

Validate before calling

k = max(1, min(num_eigenvectors, len(graph)))

Type guard

def valid_k(k: int, num_nodes: int) -> bool:
    return 1 <= k <= num_nodes

Prevention

When it happens

Trigger: 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).

Common situations: 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.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/f1c1e64489e9ba72. Report an issue: GitHub.