TheAlgorithms/Python · error · TypeError

All weights must be integers but got weight of type {type(wt

Error message

All weights must be integers but got weight of type {type(wt[i])} at index {i}

What it means

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.

Source

Thrown at dynamic_programming/knapsack.py:94

    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
    a filled DP table and the vector of weights

    Parameters
    ----------

    * `dp`: list of list, the table of a solved integer weight dynamic programming
      problem

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert weights to ints before the call: wt = [int(x) for x in wt] (round if fractional weights are meaningful, or scale the unit).
  2. If fractional weights are essential, scale both weights and capacity by a common factor to make them integral.
  3. Validate at ingestion: all(isinstance(x, int) for x in wt).

Example fix

# before
value, items = knapsack_with_example_solution(10, [1, 2.5, 3], [10, 20, 30])

# after
wt = [int(x) for x in [1, 2.5, 3]]
value, items = knapsack_with_example_solution(10, wt, [10, 20, 30])
Defensive patterns

Strategy: type-guard

Validate before calling

if not all(isinstance(x, int) and not isinstance(x, bool) for x in wt):
    wt = [int(x) for x in wt]
optimal, picked = knapsack_with_example_solution(w, wt, val)

Type guard

def all_int_weights(weights: list) -> bool:
    return all(isinstance(x, int) and not isinstance(x, bool) for x in weights)

Try / catch

try:
    optimal, picked = knapsack_with_example_solution(w, wt, val)
except TypeError as exc:
    if 'All weights must be integers' in str(exc):
        optimal, picked = knapsack_with_example_solution(w, [int(x) for x in wt], val)
    else:
        raise

Prevention

When it happens

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

Common situations: Weights parsed from CSV/JSON as floats ('2.0') without int conversion; mixing units (grams as floats) without scaling; None values from sparse data.

Related errors


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