{"record":{"id":"6ba0958617e8f1e5","repo":"TheAlgorithms/Python","slug":"the-length-of-profit-and-weight-must-be-same","errorCode":null,"errorMessage":"The length of profit and weight must be same.","messagePattern":"The length of profit and weight must be same\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"knapsack/greedy_knapsack.py","lineNumber":34,"sourceCode":"be carried.\n\"\"\"\n\n\ndef calc_profit(profit: list, weight: list, max_weight: int) -> int:\n    \"\"\"\n    Function description is as follows-\n    :param profit: Take a list of profits\n    :param weight: Take a list of weight if bags corresponding to the profits\n    :param max_weight: Maximum weight that could be carried\n    :return: Maximum expected gain\n\n    >>> calc_profit([1, 2, 3], [3, 4, 5], 15)\n    6\n    >>> calc_profit([10, 9 , 8], [3 ,4 , 5], 25)\n    27\n    \"\"\"\n    if len(profit) != len(weight):\n        raise ValueError(\"The length of profit and weight must be same.\")\n    if max_weight <= 0:\n        raise ValueError(\"max_weight must greater than zero.\")\n    if any(p < 0 for p in profit):\n        raise ValueError(\"Profit can not be negative.\")\n    if any(w < 0 for w in weight):\n        raise ValueError(\"Weight can not be negative.\")\n\n    # List created to store profit gained for the 1kg in case of each weight\n    # respectively.  Calculate and append profit/weight for each element.\n    profit_by_weight = [p / w for p, w in zip(profit, weight)]\n\n    # Creating a copy of the list and sorting profit/weight in ascending order\n    sorted_profit_by_weight = sorted(profit_by_weight)\n\n    # declaring useful variables\n    length = len(sorted_profit_by_weight)\n    limit = 0\n    gain = 0","sourceCodeStart":16,"sourceCodeEnd":52,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/knapsack/greedy_knapsack.py#L16-L52","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Make profit and weight come from one source: iterate items as (p, w) tuples and derive both lists from it.","Add an assert len(profit) == len(weight) at the point the lists are built, where context is richest.","Validate row completeness when parsing input files."],"exampleFix":"# before\ncalc_profit([10, 20, 30], [5, 5], 100)  # ValueError\n\n# after\nitems = [(10, 5), (20, 5), (30, 7)]\ncalc_profit([p for p, _ in items], [w for _, w in items], 100)","handlingStrategy":"validation","validationCode":"assert len(profit) == len(weight), (\n    f\"{len(profit)} profits vs {len(weight)} weights\"\n)","typeGuard":"def is_paired(profit: list[float], weight: list[float]) -> bool:\n    return len(profit) == len(weight)","tryCatchPattern":"try:\n    gain = calc_profit(profit, weight, max_weight)\nexcept ValueError as e:\n    if \"length\" in str(e).lower():\n        raise ValueError(\"item lists out of sync at construction site\") from e\n    raise","preventionTips":["Build profit and weight from a single list of item tuples.","Validate row completeness when parsing CSV input.","Assert pairing where the lists are built, not where they are used."],"tags":["knapsack","greedy","validation","input-mismatch"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}