{"record":{"id":"4db09390b6e43ea4","repo":"TheAlgorithms/Python","slug":"the-number-of-weights-must-be-the-same-as-the-numb","errorCode":null,"errorMessage":"The number of weights must be the same as the number of values.\nBut got {num_items} weights and {len(val)} values","messagePattern":"The number of weights must be the same as the number of values\\.\nBut got (.+?) weights and (.+?) values","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"dynamic_programming/knapsack.py","lineNumber":87,"sourceCode":"    (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\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","sourceCodeStart":69,"sourceCodeEnd":105,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/dynamic_programming/knapsack.py#L69-L105","documentation":"Raised by knapsack_with_example_solution when len(wt) != len(val) — every item needs exactly one weight and one value for the DP table to be well formed. The message interpolates both counts ('But got {num_items} weights and {len(val)} values') so the mismatch is immediately visible. It fires after the list/tuple type check but before element-type validation.","triggerScenarios":"knapsack_with_example_solution(6, [4,3,2,3], [3,2,4]) as in the doctest (4 weights, 3 values); dropping or adding one element to only one vector during data cleaning; zipping weights and values from sources that got out of sync.","commonSituations":"Loading weights and values from separate CSV columns where a row has a missing/extra field; partial updates to config lists; copy-paste errors in test fixtures.","solutions":["Align the vectors before calling: truncate or pad so len(wt) == len(val), or reject the dataset upstream.","Validate at load time: if len(weights) != len(values): raise ValueError in your data loader.","Read the counts in the message to find which vector is off and by how much."],"exampleFix":"# before\nresult = knapsack_with_example_solution(w, weights, values)  # lengths differ\n\n# after\nif len(weights) != len(values):\n    raise ValueError(f'weights/values mismatch: {len(weights)} vs {len(values)}')\nresult = knapsack_with_example_solution(w, weights, values)","handlingStrategy":"validation","validationCode":"if len(wt) != len(val):\n    raise ValueError(f'weights ({len(wt)}) and values ({len(val)}) must have equal length')\noptimal, picked = knapsack_with_example_solution(w, wt, val)","typeGuard":"def equal_length(a: list, b: list) -> bool:\n    return len(a) == len(b)","tryCatchPattern":"try:\n    optimal, picked = knapsack_with_example_solution(w, wt, val)\nexcept ValueError as exc:\n    if 'number of weights' in str(exc):\n        raise ValueError('item data out of sync; re-check data source') from exc\n    raise","preventionTips":["Store per-item (weight, value) pairs together and unzip at call time instead of keeping parallel lists.","Validate paired vectors at data-load time, not at algorithm call time.","Parse CSVs with per-row validation so one bad row cannot desynchronize columns."],"tags":["python","input-validation","length-mismatch","dynamic-programming"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}