TheAlgorithms/Python · error · ValueError

Invalid weight of {weight:f} provided

Error message

Invalid weight of {weight:f} provided

What it means

Raised by the scoring loop in scoring_algorithm when the weight argument for a criterion is neither 0 nor 1. Weight 0 produces rank-based scores, weight 1 produces min-max normalized scores, and there is no interpolation between them, so any other value is invalid.

Source

Thrown at other/scoring_algorithm.py:73

        # for weight 0 score is 1 - actual score
        if weight == 0:
            for item in dlist:
                try:
                    score.append(1 - ((item - mind) / (maxd - mind)))
                except ZeroDivisionError:
                    score.append(1)

        elif weight == 1:
            for item in dlist:
                try:
                    score.append((item - mind) / (maxd - mind))
                except ZeroDivisionError:
                    score.append(0)

        # weight not 0 or 1
        else:
            msg = f"Invalid weight of {weight:f} provided"
            raise ValueError(msg)

        score_lists.append(score)

    return score_lists


def generate_final_scores(score_lists: list[list[float]]) -> list[float]:
    """
    >>> generate_final_scores([[1.0, 0.0, 0.33333333333333337],
    ...                        [0.75, 0.0, 1.0],
    ...                        [0.25, 1.0, 0.0]])
    [2.0, 1.0, 1.3333333333333335]
    """
    # initialize final scores
    final_scores: list[float] = [0 for i in range(len(score_lists[0]))]

    for slist in score_lists:
        for j, ele in enumerate(slist):

View on GitHub (pinned to f5988cc097)

Solutions

  1. Use only 0 (rank-based) or 1 (min-max) for each criterion's weight
  2. If you need custom mixing, compute both score lists with weights 0 and 1 and blend them yourself afterwards
  3. Validate the weights list up front: assert all(w in (0, 1) for w in weights)

Example fix

# before
score_lists = calculate_scores(..., weights=[0, 0.5, 1])  # ValueError on 0.5

# after
rank_scores = calculate_scores(..., weights=[0, 0, 0])
minmax_scores = calculate_scores(..., weights=[1, 1, 1])
# blend rank/min-max per criterion yourself if intermediate behavior is needed
Defensive patterns

Strategy: validation

Validate before calling

def valid_weights(weights) -> bool:
    return all(w in (0, 1) for w in weights)

Prevention

When it happens

Trigger: Calling the scoring function with weights like 0.5, 2, or -1 for any criterion in the weights list — e.g. weights=[0, 0.5, 1] fails on the second element.

Common situations: Assuming weights are continuous mixing coefficients (0.0-1.0) as in weighted-sum scoring models, or loading weights from config where an intermediate value was entered.

Related errors


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