TheAlgorithms/Python · error · ValueError

The length of profit and weight must be same.

Error message

The length of profit and weight must be same.

What it means

Thrown by calc_profit() (greedy fractional knapsack) when len(profit) != len(weight). Profits and weights are paired element-wise (profit[i] belongs to item i with weight[i]); mismatched lists would silently mis-pair items, so the function validates lengths first and raises ValueError.

Source

Thrown at knapsack/greedy_knapsack.py:34

be carried.
"""


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

View on GitHub (pinned to f5988cc097)

Solutions

  1. Make profit and weight come from one source: iterate items as (p, w) tuples and derive both lists from it.
  2. Add an assert len(profit) == len(weight) at the point the lists are built, where context is richest.
  3. Validate row completeness when parsing input files.

Example fix

# before
calc_profit([10, 20, 30], [5, 5], 100)  # ValueError

# after
items = [(10, 5), (20, 5), (30, 7)]
calc_profit([p for p, _ in items], [w for _, w in items], 100)
Defensive patterns

Strategy: validation

Validate before calling

assert len(profit) == len(weight), (
    f"{len(profit)} profits vs {len(weight)} weights"
)

Type guard

def is_paired(profit: list[float], weight: list[float]) -> bool:
    return len(profit) == len(weight)

Try / catch

try:
    gain = calc_profit(profit, weight, max_weight)
except ValueError as e:
    if "length" in str(e).lower():
        raise ValueError("item lists out of sync at construction site") from e
    raise

Prevention

When it happens

Trigger: Calling calc_profit([10, 20, 30], [5, 5], 100) — three profits, two weights. Common when lists are built by separate loops/comprehensions with different filter conditions, or when one list is appended to later than the other.

Common situations: Data ingestion where a malformed row drops a weight but not a profit; refactoring that adds an item to one list only; CSV columns with ragged rows.

Related errors


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