{"record":{"id":"4d16975055ef2076","repo":"TheAlgorithms/Python","slug":"resistor-at-index-index-has-a-negative-value","errorCode":null,"errorMessage":"Resistor at index {index} has a negative value!","messagePattern":"Resistor at index (.+?) has a negative value!","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"electronics/resistor_equivalence.py","lineNumber":49,"sourceCode":"def resistor_series(resistors: list[float]) -> float:\n    \"\"\"\n    Req = R1 + R2 + ... + Rn\n\n    Calculate the equivalent resistance for any number of resistors in parallel.\n\n    >>> resistor_series([3.21389, 2, 3])\n    8.21389\n    >>> resistor_series([3.21389, 2, -3])\n    Traceback (most recent call last):\n        ...\n    ValueError: Resistor at index 2 has a negative value!\n    \"\"\"\n    sum_r = 0.00\n    for index, resistor in enumerate(resistors):\n        sum_r += resistor\n        if resistor < 0:\n            msg = f\"Resistor at index {index} has a negative value!\"\n            raise ValueError(msg)\n    return sum_r\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n","sourceCodeStart":31,"sourceCodeEnd":57,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/electronics/resistor_equivalence.py#L31-L57","documentation":"Raised by resistor_series() in electronics/resistor_equivalence.py when any element of the resistors list is negative. Unlike the parallel function, zero is allowed here (a 0-ohm link is physically fine in a series chain); only strictly negative values are rejected, again naming the 0-based index of the offending element. Note the check fires after the value is added to the running sum, but since it raises, the partial sum is discarded.","triggerScenarios":"resistor_series([3.21389, 2, -3]) — any negative element; sign errors in parsed data such as '-4.7' meaning 4.7 ohms; subtraction artifacts like -0.0 from floating-point cleanup.","commonSituations":"Datasheets or CSVs encoding tolerance as signed deltas that get merged into the value column; unit conversion bugs producing negatives; reusing validation logic written for resistor_parallel (which also rejects 0) and being surprised 0 passes here.","solutions":["Sanitize inputs: take abs() only if you know the sign is a data-entry artifact, otherwise reject the record.","Validate `all(r >= 0 for r in resistors)` before calling if you want to fail fast with your own message.","Catch ValueError and log the reported index to locate the bad row in the source data."],"exampleFix":"# before\nr = resistor_series([3.21389, 2, -3])  # ValueError: index 2\n\n# after\nr = resistor_series([3.21389, 2, 3])","handlingStrategy":"validation","validationCode":"if any(r < 0 for r in resistors):\n    bad = [i for i, r in enumerate(resistors) if r < 0]\n    raise UserInputError(f\"Negative resistance at indices {bad}; check sign of parsed values\")","typeGuard":"def all_non_negative(vals: list[float]) -> bool:\n    return all(r >= 0 for r in vals)  # 0 ohm links are valid in series","tryCatchPattern":"try:\n    total = resistor_series(resistors)\nexcept ValueError as exc:\n    total = None\n    log_bad_row(str(exc))","preventionTips":["Validate sign at CSV parse time.","Note series allows 0 but parallel does not — do not share one validator blindly.","Watch for -0.0 from floating-point cleanup."],"tags":["electronics","resistor","series","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}