TheAlgorithms/Python · error · ValueError

n and r must be non-negative integers

Error message

n and r must be non-negative integers

What it means

binomial_coefficient(n, r) computes C(n, r) with a Pascal-row DP. It raises ValueError('n and r must be non-negative integers') when n < 0 or r < 0; note it does not type-check, so floats fall through to a TypeError from range() instead.

Source

Thrown at maths/binomial_coefficient.py:43

    >>> binomial_coefficient(-2, 3)
    Traceback (most recent call last):
        ...
    ValueError: n and r must be non-negative integers
    >>> binomial_coefficient(5, -1)
    Traceback (most recent call last):
        ...
    ValueError: n and r must be non-negative integers
    >>> binomial_coefficient(10.1, 5)
    Traceback (most recent call last):
        ...
    TypeError: 'float' object cannot be interpreted as an integer
    >>> binomial_coefficient(10, 5.1)
    Traceback (most recent call last):
        ...
    TypeError: 'float' object cannot be interpreted as an integer
    """
    if n < 0 or r < 0:
        raise ValueError("n and r must be non-negative integers")
    if 0 in (n, r):
        return 1
    c = [0 for i in range(r + 1)]
    # nc0 = 1
    c[0] = 1
    for i in range(1, n + 1):
        # to compute current row from previous row.
        j = min(i, r)
        while j > 0:
            c[j] += c[j - 1]
            j -= 1
    return c[r]


if __name__ == "__main__":
    from doctest import testmod

    testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Validate n >= 0 and r >= 0 before calling.
  2. Coerce float inputs with int() when they are whole numbers.
  3. For r > n, know the function returns a row value rather than erroring — check that case separately if you need C(n,r)=0 semantics.

Example fix

# before
c = binomial_coefficient(n, k - n)  # negative when k < n

# after
r = k - n
c = binomial_coefficient(n, r) if r >= 0 else 0
Defensive patterns

Strategy: validation

Validate before calling

if n < 0 or r < 0:
    raise ValueError(f"n and r must be non-negative: n={n}, r={r}")
if not isinstance(n, int) or not isinstance(r, int):
    raise TypeError("n and r must be integers")
c = binomial_coefficient(n, r)

Type guard

def valid_binom_args(n: object, r: object) -> bool:
    return isinstance(n, int) and isinstance(r, int) and n >= 0 and r >= 0

Prevention

When it happens

Trigger: binomial_coefficient(-1, 5); binomial_coefficient(10, -2); negative r from an r = k - n computation where k < n.

Common situations: Combinatorics loops with underflowing indices; deriving r via subtraction; passing parsed floats like 10.0 will NOT raise this error but a later TypeError — sanitize types too.

Related errors


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