{"record":{"id":"21f332e4b5dbbc4b","repo":"TheAlgorithms/Python","slug":"all-weights-must-be-integers-but-got-weight-of-typ","errorCode":null,"errorMessage":"All weights must be integers but got weight of type {type(wt[i])} at index {i}","messagePattern":"All weights must be integers but got weight of type (.+?) at index (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"dynamic_programming/knapsack.py","lineNumber":94,"sourceCode":"    if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))):\n        raise ValueError(\n            \"Both the weights and values vectors must be either lists or tuples\"\n        )\n\n    num_items = len(wt)\n    if num_items != len(val):\n        msg = (\n            \"The number of weights must be the same as the number of values.\\n\"\n            f\"But got {num_items} weights and {len(val)} values\"\n        )\n        raise ValueError(msg)\n    for i in range(num_items):\n        if not isinstance(wt[i], int):\n            msg = (\n                \"All weights must be integers but got weight of \"\n                f\"type {type(wt[i])} at index {i}\"\n            )\n            raise TypeError(msg)\n\n    optimal_val, dp_table = knapsack(w, wt, val, num_items)\n    example_optional_set: set = set()\n    _construct_solution(dp_table, wt, num_items, w, example_optional_set)\n\n    return optimal_val, example_optional_set\n\n\ndef _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):\n    \"\"\"\n    Recursively reconstructs one of the optimal subsets given\n    a filled DP table and the vector of weights\n\n    Parameters\n    ----------\n\n    * `dp`: list of list, the table of a solved integer weight dynamic programming\n      problem","sourceCodeStart":76,"sourceCodeEnd":112,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/dynamic_programming/knapsack.py#L76-L112","documentation":"Raised as a TypeError by knapsack_with_example_solution when any element of the weights vector fails isinstance(wt[i], int). The DP indexing and comparisons assume integer weights, so floats (e.g. 2.5), strings, and None in wt trigger this at the first offending index, which is reported in the message along with the actual type. Note only weights are checked element-wise; values are not.","triggerScenarios":"knapsack(10, [1, 2.5, 3], [10, 20, 30]) — the float 2.5 at index 1 raises TypeError; string weights from unconverted user input; bool passes (subclass of int) but is almost always a data bug.","commonSituations":"Weights parsed from CSV/JSON as floats ('2.0') without int conversion; mixing units (grams as floats) without scaling; None values from sparse data.","solutions":["Convert weights to ints before the call: wt = [int(x) for x in wt] (round if fractional weights are meaningful, or scale the unit).","If fractional weights are essential, scale both weights and capacity by a common factor to make them integral.","Validate at ingestion: all(isinstance(x, int) for x in wt)."],"exampleFix":"# before\nvalue, items = knapsack_with_example_solution(10, [1, 2.5, 3], [10, 20, 30])\n\n# after\nwt = [int(x) for x in [1, 2.5, 3]]\nvalue, items = knapsack_with_example_solution(10, wt, [10, 20, 30])","handlingStrategy":"type-guard","validationCode":"if not all(isinstance(x, int) and not isinstance(x, bool) for x in wt):\n    wt = [int(x) for x in wt]\noptimal, picked = knapsack_with_example_solution(w, wt, val)","typeGuard":"def all_int_weights(weights: list) -> bool:\n    return all(isinstance(x, int) and not isinstance(x, bool) for x in weights)","tryCatchPattern":"try:\n    optimal, picked = knapsack_with_example_solution(w, wt, val)\nexcept TypeError as exc:\n    if 'All weights must be integers' in str(exc):\n        optimal, picked = knapsack_with_example_solution(w, [int(x) for x in wt], val)\n    else:\n        raise","preventionTips":["Convert CSV/JSON numbers with int() when the domain demands integral weights.","Scale fractional weights by a common factor rather than hoping floats pass.","Exclude bool in weight validation — True/False silently pass isinstance(int) checks."],"tags":["python","type-error","input-validation","dynamic-programming"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}