TheAlgorithms/Python · error · ValueError

the value of input must not be a negative number

Error message

the value of input must not be a negative number

What it means

Raised by minimum_squares_to_represent_a_number(number) when number < 0, after the integrality check has already passed. Negative numbers would create a negative-size answers list ([-1] * (number + 1) with number + 1 <= 0), so they are rejected with this ValueError. The doctest documents minimum_squares_to_represent_a_number(-1) raising it.

Source

Thrown at dynamic_programming/minimum_squares_to_represent_a_number.py:31

    >>> minimum_squares_to_represent_a_number(21)
    3
    >>> minimum_squares_to_represent_a_number(58)
    2
    >>> minimum_squares_to_represent_a_number(-1)
    Traceback (most recent call last):
        ...
    ValueError: the value of input must not be a negative number
    >>> minimum_squares_to_represent_a_number(0)
    1
    >>> minimum_squares_to_represent_a_number(12.34)
    Traceback (most recent call last):
        ...
    ValueError: the value of input must be a natural number
    """
    if number != int(number):
        raise ValueError("the value of input must be a natural number")
    if number < 0:
        raise ValueError("the value of input must not be a negative number")
    if number == 0:
        return 1
    answers = [-1] * (number + 1)
    answers[0] = 0
    for i in range(1, number + 1):
        answer = sys.maxsize
        root = int(math.sqrt(i))
        for j in range(1, root + 1):
            current_answer = 1 + answers[i - (j**2)]
            answer = min(answer, current_answer)
        answers[i] = answer
    return answers[number]


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Guard at the call site: only call when number >= 0, e.g. via max(0, number) if clamping suits your domain.
  2. Fix the upstream computation producing the negative value.
  3. Validate parsed input early: if number < 0: reject with your own error message.

Example fix

# before
squares = minimum_squares_to_represent_a_number(delta)  # delta = -5 -> ValueError

# after
if delta < 0:
    raise ValueError('delta must be non-negative')
squares = minimum_squares_to_represent_a_number(delta)
Defensive patterns

Strategy: validation

Validate before calling

if number < 0:
    raise ValueError(f'number must be >= 0, got {number}')
count = minimum_squares_to_represent_a_number(number)

Type guard

def is_non_negative_number(value: object) -> bool:
    return isinstance(value, (int, float)) and value >= 0

Try / catch

try:
    count = minimum_squares_to_represent_a_number(number)
except ValueError as exc:
    if 'negative number' in str(exc):
        raise ValueError('input underflowed below zero; check upstream math') from exc
    raise

Prevention

When it happens

Trigger: minimum_squares_to_represent_a_number(-1) or any negative integral value; -3.0 also reaches this check because -3.0 == int(-3.0) passes the first guard and then compares negative.

Common situations: Unvalidated user input; arithmetic that underflows below zero (a - b with b > a); sign errors when converting signed deltas to counts.

Related errors


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