TheAlgorithms/Python · error · ValueError

Invalid input needed_sum must be between 1 and 1000, power b

Error message

Invalid input
needed_sum must be between 1 and 1000, power between 2 and 10.

What it means

Raised by center_of_mass() in physics/center_of_mass.py when the particles list is empty. The center of mass R = sum(m_i*r_i)/sum(m_i) is undefined with no particles (0/0), so the function refuses empty input before dividing. The check is 'if not particles', so any empty sequence (list, tuple) triggers it.

Source

Thrown at backtracking/power_sum.py:80

    >>> solve(20, 2)
    1
    >>> solve(15, 10)
    0
    >>> solve(16, 2)
    1
    >>> solve(20, 1)
    Traceback (most recent call last):
        ...
    ValueError: Invalid input
    needed_sum must be between 1 and 1000, power between 2 and 10.
    >>> solve(-10, 5)
    Traceback (most recent call last):
        ...
    ValueError: Invalid input
    needed_sum must be between 1 and 1000, power between 2 and 10.
    """
    if not (1 <= needed_sum <= 1000 and 2 <= power <= 10):
        raise ValueError(
            "Invalid input\n"
            "needed_sum must be between 1 and 1000, power between 2 and 10."
        )

    return backtrack(needed_sum, power, 1, 0, 0)[1]  # Return the solutions_count


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Skip or special-case empty particle sets before calling: if not particles: continue / return None.
  2. Check the upstream filter/loader that produced the list to see why it is empty.
  3. Catch ValueError at the batch level to skip bad frames without aborting the run.

Example fix

# before
com = center_of_mass([p for p in frame if p.mass > 100])  # may be []

# after
sel = [p for p in frame if p.mass > 100]
com = center_of_mass(sel) if sel else None
Defensive patterns

Strategy: validation

Validate before calling

if not particles:
    return None  # or skip frame
com = center_of_mass(particles)

Type guard

def is_nonempty_particle_list(ps: object) -> bool:
    return isinstance(ps, list) and len(ps) > 0 and all(hasattr(p, 'mass') for p in ps)

Try / catch

try:
    com = center_of_mass(frame_particles)
except ValueError:
    continue  # skip empty frames in batch processing

Prevention

When it happens

Trigger: center_of_mass([]); center_of_mass(particles[:0]); passing a list produced by a filter comprehension that matched nothing, e.g. [p for p in particles if p.mass > 100] on data with no such particles.

Common situations: Batch processing of simulation frames where some frames contain zero particles after filtering/culling; loading a dataset whose parser returned an empty list on a malformed file.

Related errors


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