TheAlgorithms/Python · error · ValueError

The number of weights must be the same as the number of valu

Error message

The number of weights must be the same as the number of values.
But got {num_items} weights and {len(val)} values

What it means

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.

Source

Thrown at dynamic_programming/knapsack.py:87

    (8, {3, 4})
    >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4])
    Traceback (most recent call last):
        ...
    ValueError: The number of weights must be the same as the number of values.
    But got 4 weights and 3 values
    """
    if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))):
        raise ValueError(
            "Both the weights and values vectors must be either lists or tuples"
        )

    num_items = len(wt)
    if num_items != len(val):
        msg = (
            "The number of weights must be the same as the number of values.\n"
            f"But got {num_items} weights and {len(val)} values"
        )
        raise ValueError(msg)
    for i in range(num_items):
        if not isinstance(wt[i], int):
            msg = (
                "All weights must be integers but got weight of "
                f"type {type(wt[i])} at index {i}"
            )
            raise TypeError(msg)

    optimal_val, dp_table = knapsack(w, wt, val, num_items)
    example_optional_set: set = set()
    _construct_solution(dp_table, wt, num_items, w, example_optional_set)

    return optimal_val, example_optional_set


def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):
    """
    Recursively reconstructs one of the optimal subsets given

View on GitHub (pinned to f5988cc097)

Solutions

  1. Align the vectors before calling: truncate or pad so len(wt) == len(val), or reject the dataset upstream.
  2. Validate at load time: if len(weights) != len(values): raise ValueError in your data loader.
  3. Read the counts in the message to find which vector is off and by how much.

Example fix

# before
result = knapsack_with_example_solution(w, weights, values)  # lengths differ

# after
if len(weights) != len(values):
    raise ValueError(f'weights/values mismatch: {len(weights)} vs {len(values)}')
result = knapsack_with_example_solution(w, weights, values)
Defensive patterns

Strategy: validation

Validate before calling

if len(wt) != len(val):
    raise ValueError(f'weights ({len(wt)}) and values ({len(val)}) must have equal length')
optimal, picked = knapsack_with_example_solution(w, wt, val)

Type guard

def equal_length(a: list, b: list) -> bool:
    return len(a) == len(b)

Try / catch

try:
    optimal, picked = knapsack_with_example_solution(w, wt, val)
except ValueError as exc:
    if 'number of weights' in str(exc):
        raise ValueError('item data out of sync; re-check data source') from exc
    raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/4db09390b6e43ea4. Report an issue: GitHub.