{"record":{"id":"eb862d03ca4e79a9","repo":"TheAlgorithms/Python","slug":"both-the-weights-and-values-vectors-must-be-either","errorCode":null,"errorMessage":"Both the weights and values vectors must be either lists or tuples","messagePattern":"Both the weights and values vectors must be either lists or tuples","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"dynamic_programming/knapsack.py","lineNumber":77,"sourceCode":"    * `optimal_val`: float, the optimal value for the given knapsack problem\n    * `example_optional_set`: set, the indices of one of the optimal subsets\n      which gave rise to the optimal value.\n\n    Examples\n    --------\n\n    >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22])\n    (142, {2, 3, 4})\n    >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4])\n    (8, {3, 4})\n    >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4])\n    Traceback (most recent call last):\n        ...\n    ValueError: The number of weights must be the same as the number of values.\n    But got 4 weights and 3 values\n    \"\"\"\n    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","sourceCodeStart":59,"sourceCodeEnd":95,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/dynamic_programming/knapsack.py#L59-L95","documentation":"Raised by knapsack_with_example_solution(w, wt, val) when either wt or val is not a list or tuple (checked with isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))). The 0/1 knapsack DP needs indexed access to weights and values, so generators and other sequences are rejected. It is the first validation in the function, before length and element-type checks.","triggerScenarios":"Passing a generator or map object, e.g. knapsack_with_example_solution(10, map(abs, w), [1,2,3,4]); passing a numpy array, set, or string as weights or values; passing None for one of the vectors.","commonSituations":"Chaining map/filter generators from upstream data processing; using numpy arrays from numerical pipelines without conversion; JSON deserialization yielding something other than arrays.","solutions":["Materialize sequences before the call: knapsack(w, list(wt), list(val)).","Convert numpy arrays with .tolist().","Add a precondition assert isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))."],"exampleFix":"# before\nbest = knapsack_with_example_solution(10, (abs(x) for x in raw), [1,2,3,4])\n\n# after\nbest = knapsack_with_example_solution(10, [abs(x) for x in raw], [1,2,3,4])","handlingStrategy":"type-guard","validationCode":"if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))):\n    wt, val = list(wt), list(val)\noptimal, picked = knapsack_with_example_solution(w, wt, val)","typeGuard":"def is_sequence_pair(a: object, b: object) -> bool:\n    return isinstance(a, (list, tuple)) and isinstance(b, (list, tuple))","tryCatchPattern":"try:\n    optimal, picked = knapsack_with_example_solution(w, wt, val)\nexcept ValueError as exc:\n    if 'lists or tuples' in str(exc):\n        optimal, picked = knapsack_with_example_solution(w, list(wt), list(val))\n    else:\n        raise","preventionTips":["Materialize generators with list() before passing to DP functions that index repeatedly.","Convert numpy arrays with .tolist() at the boundary of pure-Python libraries.","Standardize on lists for item vectors across your codebase."],"tags":["python","input-validation","dynamic-programming","knapsack"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}