TheAlgorithms/Python · error · ValueError

The number of coefficients should be equal to the degree + 1

Error message

The number of coefficients should be equal to the degree + 1.

What it means

Polynomial.__init__ in maths/polynomials/single_indeterminate_operations.py builds a single-variable polynomial from a degree and coefficients ordered lowest-power-first. It requires len(coefficients) == degree + 1 exactly (degree d has terms x^0..x^d) and raises ValueError('The number of coefficients should be equal to the degree + 1.') otherwise. The invariant is load-bearing: every later operation (__add__, evaluation, string formatting) indexes coefficients[i] as the i-th power, so a mismatched list would silently produce wrong polynomials.

Source

Thrown at maths/polynomials/single_indeterminate_operations.py:27

from __future__ import annotations

from collections.abc import MutableSequence


class Polynomial:
    def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None:
        """
        The coefficients should be in order of degree, from smallest to largest.
        >>> p = Polynomial(2, [1, 2, 3])
        >>> p = Polynomial(2, [1, 2, 3, 4])
        Traceback (most recent call last):
        ...
        ValueError: The number of coefficients should be equal to the degree + 1.

        """
        if len(coefficients) != degree + 1:
            raise ValueError(
                "The number of coefficients should be equal to the degree + 1."
            )

        self.coefficients: list[float] = list(coefficients)
        self.degree = degree

    def __add__(self, polynomial_2: Polynomial) -> Polynomial:
        """
        Polynomial addition
        >>> p = Polynomial(2, [1, 2, 3])
        >>> q = Polynomial(2, [1, 2, 3])
        >>> p + q
        6x^2 + 4x + 2
        """

        if self.degree > polynomial_2.degree:
            coefficients = self.coefficients[:]
            for i in range(polynomial_2.degree + 1):

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass degree = len(coefficients) - 1 so the pair is consistent by construction.
  2. Fix the coefficient list to include every power from x^0 to x^d, using explicit 0.0 for missing middle terms.
  3. Write a tiny helper that validates/normalizes (strips leading zeros at the high end and recomputes degree) before constructing.

Example fix

# before
p = Polynomial(2, [1, 2, 3, 4])  # ValueError

# after
coeffs = [1, 2, 3, 4]
p = Polynomial(len(coeffs) - 1, coeffs)
Defensive patterns

Strategy: validation

Validate before calling

assert len(coefficients) == degree + 1, (degree, len(coefficients))
p = Polynomial(degree, coefficients)
# or derive degree from the data:
p = Polynomial(len(coefficients) - 1, coefficients)

Try / catch

try:
    Polynomial(degree, coeffs)
except ValueError:
    degree = len(coeffs) - 1  # self-heal only if coeffs are authoritative

Prevention

When it happens

Trigger: Constructing Polynomial(2, [1, 2, 3, 4]) (4 coefficients for degree 2), Polynomial(3, [1, 2]) (too few), or computing degree from data but building the coefficient list by another route (e.g. stripping leading zeros or appending a constant) so the lengths diverge.

Common situations: Deducing degree from a model-fit output while hand-building coefficients; copying example lists and editing them; off-by-one confusion about whether degree means 'highest power' (it does) vs 'number of terms'.

Related errors


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