TheAlgorithms/Python · error · ValueError

Resistor at index {index} has a negative or zero value!

Error message

Resistor at index {index} has a negative or zero value!

What it means

Raised by resistor_parallel() in electronics/resistor_equivalence.py when any element of the resistors list is <= 0. The formula computes 1/sum(1/Ri), and a zero resistance would divide by zero while a negative one is physically meaningless, so the function validates each element (using its 0-based list index in the message) before accumulating.

Source

Thrown at electronics/resistor_equivalence.py:26

    Req = 1/ (1/R1 + 1/R2 + ... + 1/Rn)

    >>> resistor_parallel([3.21389, 2, 3])
    0.8737571620498019
    >>> resistor_parallel([3.21389, 2, -3])
    Traceback (most recent call last):
        ...
    ValueError: Resistor at index 2 has a negative or zero value!
    >>> resistor_parallel([3.21389, 2, 0.000])
    Traceback (most recent call last):
        ...
    ValueError: Resistor at index 2 has a negative or zero value!
    """

    first_sum = 0.00
    for index, resistor in enumerate(resistors):
        if resistor <= 0:
            msg = f"Resistor at index {index} has a negative or zero value!"
            raise ValueError(msg)
        first_sum += 1 / float(resistor)
    return 1 / first_sum


def resistor_series(resistors: list[float]) -> float:
    """
    Req = R1 + R2 + ... + Rn

    Calculate the equivalent resistance for any number of resistors in parallel.

    >>> resistor_series([3.21389, 2, 3])
    8.21389
    >>> resistor_series([3.21389, 2, -3])
    Traceback (most recent call last):
        ...
    ValueError: Resistor at index 2 has a negative value!
    """
    sum_r = 0.00

View on GitHub (pinned to f5988cc097)

Solutions

  1. Filter or reject non-positive measurements at ingestion: `vals = [r for r in resistors if r > 0]` only if zero truly means 'no resistor present'.
  2. Treat 0 as 'absent branch' and remove that resistor before calling, since an absent branch does not change a parallel combination.
  3. Fix the upstream measurement/calibration so real resistances are positive.
  4. Wrap in try/except ValueError and report the offending index to the operator.

Example fix

# before
r = resistor_parallel([3.21389, 2, 0.000])  # ValueError: index 2

# after
vals = [r for r in [3.21389, 2, 0.000] if r > 0]  # drop absent/shorted branches
r = resistor_parallel(vals)
Defensive patterns

Strategy: validation

Validate before calling

def clean_parallel_branches(resistors: list[float]) -> list[float]:
    # 0-ohm branch = short -> invalid; treat 0 as absent branch only if that is your intent
    bad = [i for i, r in enumerate(resistors) if r <= 0]
    if bad:
        raise UserInputError(f"Non-positive resistance at indices {bad}")
    return resistors

Type guard

def all_positive(vals: list[float]) -> bool:
    return all(isinstance(r, (int, float)) and r > 0 for r in vals)

Try / catch

try:
    req = resistor_parallel(resistors)
except ValueError as exc:
    raise MeasurementError(f"Bad channel: {exc}") from exc

Prevention

When it happens

Trigger: resistor_parallel([3.21389, 2, 0.000]) or resistor_parallel([10, -4.7, 3]) — any zero or negative element, at the index named in the message; empty sensor reads that default to 0.0 fed straight into the call.

Common situations: Hardware measurements where a channel reads 0 before calibration; CSV rows with missing values parsed as 0; mixing up series/parallel helpers and passing an intended series list containing a placeholder 0.

Related errors


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