{"record":{"id":"cc05dd4dbdf4e5ae","repo":"TheAlgorithms/Python","slug":"weight-can-not-be-negative","errorCode":null,"errorMessage":"Weight can not be negative.","messagePattern":"Weight can not be negative\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"knapsack/greedy_knapsack.py","lineNumber":40,"sourceCode":"    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\n    i = 0\n\n    # loop till the total weight do not reach max limit e.g. 15 kg and till i<length\n    while limit <= max_weight and i < length:\n        # flag value for encountered greatest element in sorted_profit_by_weight\n        biggest_profit_by_weight = sorted_profit_by_weight[length - i - 1]","sourceCodeStart":22,"sourceCodeEnd":58,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/knapsack/greedy_knapsack.py#L22-L58","documentation":"Thrown by calc_profit() when any element of weight is negative. Negative weights break the greedy knapsack invariant (taking an item consumes capacity) and would also cause a ZeroDivisionError later in profit_by_weight = [p / w ...] if a zero slipped through, so all weights must be non-negative (and in practice positive).","triggerScenarios":"Calling calc_profit with a weight list containing a negative value, e.g. calc_profit([10, 20], [-5, 5], 100). Also any zero weight would pass this guard but crash on division — validate positivity yourself.","commonSituations":"Signed weights from a data feed (e.g. deltas); tare/offset arithmetic producing negatives; missing validation after unit conversions.","solutions":["Filter out items with weight <= 0 before calling (zero weights crash the ratio computation even though the guard only checks negatives).","Fix the data source so weights are physical, positive quantities.","Assert all(w > 0 for w in weight) where the list is constructed."],"exampleFix":"# before\ncalc_profit([10, 20], [-5, 5], 100)  # ValueError\n\n# after\npairs = [(p, w) for p, w in zip(profit, weight) if w > 0]\ncalc_profit([p for p, _ in pairs], [w for _, w in pairs], 100)","handlingStrategy":"validation","validationCode":"assert all(w > 0 for w in weight), \"weights must be positive\"\n# (zero weights also crash the internal p/w division even though the guard checks only negatives)","typeGuard":"def all_weights_positive(weight: list[float]) -> bool:\n    return all(isinstance(w, (int, float)) and w > 0 for w in weight)","tryCatchPattern":"try:\n    gain = calc_profit(profit, weight, max_weight)\nexcept ValueError as e:\n    if \"Weight\" in str(e):\n        keep = [(p, w) for p, w in zip(profit, weight) if w > 0]\n        gain = calc_profit([p for p, _ in keep], [w for _, w in keep], max_weight)\n    else:\n        raise","preventionTips":["Reject weight <= 0 items before the call (zero divides later).","Validate physical quantities at the data source.","Unit-test with degenerate items so the contract is explicit."],"tags":["knapsack","greedy","validation","data-quality"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}