TheAlgorithms/Python · error · ValueError

n must be greater than or equal to 0. Got n = {n}

Error message

n must be greater than or equal to 0. Got n = {n}

What it means

Raised by the shared argument-check helper (validate _style function at dynamic_programming/rod_cutting.py:190) used by top_down_cut_rod, bottom_up_cut_rod, and related rod-cutting entry points. The rod length n must be a non-negative integer because it indexes the memo/table dimension. Negative n is meaningless physically and would break indexing.

Source

Thrown at dynamic_programming/rod_cutting.py:190

        max_rev[i] = max_revenue_i

    return max_rev[n]


def _enforce_args(n: int, prices: list):
    """
    Basic checks on the arguments to the rod-cutting algorithms

    * `n`: int, the length of the rod
    * `prices`: list, the price list for each piece of rod.

    Throws ``ValueError``:
        if `n` is negative or there are fewer items in the price list than the length of
        the rod
    """
    if n < 0:
        msg = f"n must be greater than or equal to 0. Got n = {n}"
        raise ValueError(msg)

    if n > len(prices):
        msg = (
            "Each integral piece of rod must have a corresponding price. "
            f"Got n = {n} but length of prices = {len(prices)}"
        )
        raise ValueError(msg)


def main():
    prices = [6, 10, 12, 15, 20, 23]
    n = len(prices)

    # the best revenue comes from cutting the rod into 6 pieces, each
    # of length 1 resulting in a revenue of 6 * 6 = 36.
    expected_max_revenue = 36

    max_rev_top_down = top_down_cut_rod(n, prices)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Fix the caller's arithmetic so n is always >= 0 (guard loop bounds, clamp with max(0, n)).
  2. Validate n at the boundary: if n < 0: raise ValueError early in your own code with context.
  3. Remember n = 0 is legal (empty rod, revenue 0) — only negative values fail.

Example fix

# before
n = len(prices) - cuts  # can go negative
print(top_down_cut_rod(n, prices))

# after
n = max(0, len(prices) - cuts)
print(top_down_cut_rod(n, prices))
Defensive patterns

Strategy: validation

Validate before calling

def valid_rod_args(n: int, prices: list[float]) -> bool:
    return isinstance(n, int) and n >= 0 and len(prices) >= n

Type guard

def is_valid_n(n: object) -> TypeGuard[int]:
    return type(n) is int and n >= 0

Prevention

When it happens

Trigger: Calling any rod-cutting function with negative n, e.g. top_down_cut_rod(-1, [6, 10, 12]) or bottom_up_cut_rod(-5, prices). Note n = 0 is valid and returns 0 revenue.

Common situations: Computing n as len(prices) - k or n - 1 in a loop that underflows to -1; passing a user-supplied length without a lower-bound check; subtracting a cut count larger than n.

Related errors


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