TheAlgorithms/Python · error · ValueError

Step size must be positive and non-zero.

Error message

Step size must be positive and non-zero.

What it means

Raised by array_equalization when the step_size argument is <= 0. The function scans the vector in increments of step_size to count updates needed to equalize elements, so a zero or negative step would cause an infinite loop or backwards scan; the guard rejects it up front. Valid steps are strictly positive integers (a separate check enforces the integer part).

Source

Thrown at matrix/matrix_equalization.py:31

    5
    >>> array_equalization([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 5)
    0
    >>> array_equalization([22, 22, 22, 33, 33, 33], 2)
    2
    >>> array_equalization([1, 2, 3], 0)
    Traceback (most recent call last):
    ValueError: Step size must be positive and non-zero.
    >>> array_equalization([1, 2, 3], -1)
    Traceback (most recent call last):
    ValueError: Step size must be positive and non-zero.
    >>> array_equalization([1, 2, 3], 0.5)
    Traceback (most recent call last):
    ValueError: Step size must be an integer.
    >>> array_equalization([1, 2, 3], maxsize)
    1
    """
    if step_size <= 0:
        raise ValueError("Step size must be positive and non-zero.")
    if not isinstance(step_size, int):
        raise ValueError("Step size must be an integer.")

    unique_elements = set(vector)
    min_updates = maxsize

    for element in unique_elements:
        elem_index = 0
        updates = 0
        while elem_index < len(vector):
            if vector[elem_index] != element:
                updates += 1
                elem_index += step_size
            else:
                elem_index += 1
        min_updates = min(min_updates, updates)

    return min_updates

View on GitHub (pinned to f5988cc097)

Solutions

  1. Clamp the computed step to at least 1 before calling: step = max(1, step).
  2. Validate the value at the boundary where it enters your code (CLI arg, config, function parameter) and reject <= 0 with a clear message.
  3. If the step is computed from lengths, debug why it became 0 or negative (e.g. len(a) - len(b) with a shorter than b).

Example fix

# before
step = len(batch_a) - len(batch_b)  # can be <= 0
array_equalization(vector, step)

# after
step = max(1, len(batch_a) - len(batch_b))
array_equalization(vector, step)
Defensive patterns

Strategy: validation

Validate before calling

if not isinstance(step_size, int) or step_size <= 0:
    raise ValueError(f"step_size must be a positive int, got {step_size!r}")
result = array_equalization(vector, step_size)

Type guard

def is_positive_int(x) -> bool:
    """Guard: strictly positive native integer."""
    return isinstance(x, int) and not isinstance(x, bool) and x > 0

Try / catch

try:
    result = array_equalization(vector, step)
except ValueError as e:
    if "positive and non-zero" in str(e):
        step = max(1, step)
        result = array_equalization(vector, step)
    else:
        raise

Prevention

When it happens

Trigger: Calling array_equalization(vector, 0), array_equalization(vector, -1), or passing a computed step like len(sublist) - len(other_list) that evaluates to 0 or negative. Note the <= 0 check runs before the isinstance check, so a non-numeric step that cannot be compared (e.g. a string) raises TypeError from the comparison instead.

Common situations: Deriving step_size from user input or array lengths without clamping; passing -1 as an 'all elements' sentinel from another API's convention; off-by-one errors where an empty segment yields step 0.

Related errors


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