TheAlgorithms/Python · error · ValueError

max_weight must greater than zero.

Error message

max_weight must greater than zero.

What it means

Thrown by calc_profit() when max_weight <= 0. A knapsack with zero or negative capacity can carry nothing (or is nonsensical), and the greedy loop's invariant remaining_capacity > 0 would be violated immediately, so the function rejects it with ValueError rather than returning a misleading 0.

Source

Thrown at knapsack/greedy_knapsack.py:36


def calc_profit(profit: list, weight: list, max_weight: int) -> int:
    """
    Function description is as follows-
    :param profit: Take a list of profits
    :param weight: Take a list of weight if bags corresponding to the profits
    :param max_weight: Maximum weight that could be carried
    :return: Maximum expected gain

    >>> calc_profit([1, 2, 3], [3, 4, 5], 15)
    6
    >>> calc_profit([10, 9 , 8], [3 ,4 , 5], 25)
    27
    """
    if len(profit) != len(weight):
        raise ValueError("The length of profit and weight must be same.")
    if max_weight <= 0:
        raise ValueError("max_weight must greater than zero.")
    if any(p < 0 for p in profit):
        raise ValueError("Profit can not be negative.")
    if any(w < 0 for w in weight):
        raise ValueError("Weight can not be negative.")

    # List created to store profit gained for the 1kg in case of each weight
    # respectively.  Calculate and append profit/weight for each element.
    profit_by_weight = [p / w for p, w in zip(profit, weight)]

    # Creating a copy of the list and sorting profit/weight in ascending order
    sorted_profit_by_weight = sorted(profit_by_weight)

    # declaring useful variables
    length = len(sorted_profit_by_weight)
    limit = 0
    gain = 0
    i = 0

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a strictly positive max_weight.
  2. Short-circuit at the caller: if max_weight <= 0, return 0 gain without calling.
  3. Use None (not 0) as the 'unset capacity' sentinel and validate config before the call.

Example fix

# before
calc_profit(profits, weights, remaining_space)  # remaining_space may be 0

# after
if remaining_space <= 0:
    gain = 0
else:
    gain = calc_profit(profits, weights, remaining_space)
Defensive patterns

Strategy: validation

Validate before calling

if max_weight <= 0:
    gain = 0  # nothing can be carried
else:
    gain = calc_profit(profit, weight, max_weight)

Type guard

def is_positive_capacity(max_weight: int | float) -> bool:
    return isinstance(max_weight, (int, float)) and max_weight > 0

Try / catch

try:
    gain = calc_profit(profit, weight, max_weight)
except ValueError as e:
    if "max_weight" in str(e):
        gain = 0
    else:
        raise

Prevention

When it happens

Trigger: Calling calc_profit(profit, weight, 0) or with a negative max_weight; passing a computed capacity like limit - current_load that has reached zero or gone below.

Common situations: Capacity derived from a budget/remaining-space calculation that hit zero; config files defaulting capacity to 0; unit tests using 0 as a 'no capacity' placeholder.

Related errors


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