TheAlgorithms/Python · error · ValueError
Capacity cannot be negative
Error message
Capacity cannot be negative
What it means
Thrown by fractional_cover() (greedy fractional knapsack/cover) when capacity is negative. A negative capacity is physically meaningless — no item can be taken — and silently returning 0.0 would hide the caller's bug, so the function raises ValueError. Note capacity == 0 is legal and returns 0.0.
Source
Thrown at greedy_methods/fractional_cover_problem.py:79
>>> fractional_cover(items=[], capacity=50)
0.0
>>> fractional_cover(items=[Item(10, 60)], capacity=5)
30.0
>>> fractional_cover(items=[Item(10, 60)], capacity=1)
6.0
>>> fractional_cover(items=[Item(10, 60)], capacity=0)
0.0
>>> fractional_cover(items=[Item(10, 60)], capacity=-1)
Traceback (most recent call last):
...
ValueError: Capacity cannot be negative
"""
if capacity < 0:
raise ValueError("Capacity cannot be negative")
total_value = 0.0
remaining_capacity = capacity
# Sort the items by their value-to-weight ratio in descending order
for item in sorted(items, key=attrgetter("ratio"), reverse=True):
if remaining_capacity == 0:
break
weight_taken = min(item.weight, remaining_capacity)
total_value += weight_taken * item.ratio
remaining_capacity -= weight_taken
return total_value
if __name__ == "__main__":
import doctestView on GitHub (pinned to f5988cc097)
Solutions
- Pass a non-negative capacity; clamp at the source: max(0, remaining_budget).
- Replace -1 sentinels for 'unset capacity' with None and branch before calling.
- If capacity legitimately reaches 0, keep the call — it is valid and yields 0.0.
Example fix
# before
fractional_cover(items, capacity=budget - spent) # may be negative
# after
remaining = budget - spent
if remaining < 0:
raise ValueError(f"overspent budget: {remaining}")
fractional_cover(items, capacity=remaining) Defensive patterns
Strategy: validation
Validate before calling
if capacity < 0:
raise ValueError(f"capacity must be >= 0, got {capacity}") Type guard
def is_valid_capacity(capacity: float) -> bool:
return isinstance(capacity, (int, float)) and capacity >= 0 Try / catch
try:
value = fractional_cover(items, capacity)
except ValueError as e:
if "Capacity" in str(e):
value = 0.0 # treat exhausted budget as empty cover
else:
raise Prevention
- Use None, not -1, as the 'unset capacity' sentinel.
- Clamp computed capacities at the source: max(0, budget - spent).
- Validate numeric config values once at startup.
When it happens
Trigger: Calling fractional_cover(items, capacity=-1), or passing a capacity computed as a difference (budget - used) that has gone negative, or unpacking a negative value from user input / a config file.
Common situations: Budget already consumed before the call (remaining capacity goes below zero), sign errors when converting units (e.g. passing -kg), or a default of -1 used as a 'not set' sentinel leaking into the algorithm.
Related errors
- The length of profit and weight must be same.
- max_weight must greater than zero.
- Profit can not be negative.
- Weight can not be negative.
- number must be positive
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/3ddb27ad461707a2.
Report an issue: GitHub.