TheAlgorithms/Python · error · ValueError

additive_persistence() does not accept negative values

Error message

additive_persistence() does not accept negative values

What it means

additive_persistence() in maths/persistence.py raises ValueError('additive_persistence() does not accept negative values') when an int argument is < 0. Digit-sum persistence is defined only for non-negative integers; the implementation does str(num) then int(i) over characters, and a leading '-' would crash int('-') with a less informative error, so negatives are rejected up front.

Source

Thrown at maths/persistence.py:61

    https://en.wikipedia.org/wiki/Persistence_of_a_number

    >>> additive_persistence(199)
    3
    >>> additive_persistence(-1)
    Traceback (most recent call last):
        ...
    ValueError: additive_persistence() does not accept negative values
    >>> additive_persistence("long number")
    Traceback (most recent call last):
        ...
    ValueError: additive_persistence() only accepts integral values
    """

    if not isinstance(num, int):
        raise ValueError("additive_persistence() only accepts integral values")
    if num < 0:
        raise ValueError("additive_persistence() does not accept negative values")

    steps = 0
    num_string = str(num)

    while len(num_string) != 1:
        numbers = [int(i) for i in num_string]

        total = 0
        for i in range(len(numbers)):
            total += numbers[i]

        num_string = str(total)

        steps += 1
    return steps


if __name__ == "__main__":

View on GitHub (pinned to f5988cc097)

Solutions

  1. Use abs() when the sign carries no meaning: additive_persistence(abs(num)).
  2. Range-validate (num >= 0) upstream and surface a domain-specific message.
  3. Wrap in try/except ValueError if negatives are a legitimate runtime case to skip.

Example fix

# before
additive_persistence(delta)  # ValueError when delta < 0

# after
additive_persistence(abs(delta))
Defensive patterns

Strategy: validation

Validate before calling

if num < 0:
    num = abs(num)  # or raise your own domain error
additive_persistence(num)

Try / catch

try:
    additive_persistence(num)
except ValueError as exc:
    if 'negative' in str(exc):
        num = abs(num)
    else:
        raise

Prevention

When it happens

Trigger: Calling additive_persistence(-1) or any negative int such as additive_persistence(-123). Reached only for int inputs; negative non-ints raise the integral-values error because the type guard runs first.

Common situations: Passing signed computed values (differences, offsets) without abs(); user-supplied negative numbers from a CLI argument not range-checked.

Related errors


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