{"record":{"id":"ae80f1b5a16ec536","repo":"TheAlgorithms/Python","slug":"the-number-of-coefficients-should-be-equal-to-the","errorCode":null,"errorMessage":"The number of coefficients should be equal to the degree + 1.","messagePattern":"The number of coefficients should be equal to the degree \\+ 1\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"maths/polynomials/single_indeterminate_operations.py","lineNumber":27,"sourceCode":"\nfrom __future__ import annotations\n\nfrom collections.abc import MutableSequence\n\n\nclass Polynomial:\n    def __init__(self, degree: int, coefficients: MutableSequence[float]) -> None:\n        \"\"\"\n        The coefficients should be in order of degree, from smallest to largest.\n        >>> p = Polynomial(2, [1, 2, 3])\n        >>> p = Polynomial(2, [1, 2, 3, 4])\n        Traceback (most recent call last):\n        ...\n        ValueError: The number of coefficients should be equal to the degree + 1.\n\n        \"\"\"\n        if len(coefficients) != degree + 1:\n            raise ValueError(\n                \"The number of coefficients should be equal to the degree + 1.\"\n            )\n\n        self.coefficients: list[float] = list(coefficients)\n        self.degree = degree\n\n    def __add__(self, polynomial_2: Polynomial) -> Polynomial:\n        \"\"\"\n        Polynomial addition\n        >>> p = Polynomial(2, [1, 2, 3])\n        >>> q = Polynomial(2, [1, 2, 3])\n        >>> p + q\n        6x^2 + 4x + 2\n        \"\"\"\n\n        if self.degree > polynomial_2.degree:\n            coefficients = self.coefficients[:]\n            for i in range(polynomial_2.degree + 1):","sourceCodeStart":9,"sourceCodeEnd":45,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/maths/polynomials/single_indeterminate_operations.py#L9-L45","documentation":"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.","triggerScenarios":"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.","commonSituations":"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'.","solutions":["Pass degree = len(coefficients) - 1 so the pair is consistent by construction.","Fix the coefficient list to include every power from x^0 to x^d, using explicit 0.0 for missing middle terms.","Write a tiny helper that validates/normalizes (strips leading zeros at the high end and recomputes degree) before constructing."],"exampleFix":"# before\np = Polynomial(2, [1, 2, 3, 4])  # ValueError\n\n# after\ncoeffs = [1, 2, 3, 4]\np = Polynomial(len(coeffs) - 1, coeffs)","handlingStrategy":"validation","validationCode":"assert len(coefficients) == degree + 1, (degree, len(coefficients))\np = Polynomial(degree, coefficients)\n# or derive degree from the data:\np = Polynomial(len(coefficients) - 1, coefficients)","typeGuard":null,"tryCatchPattern":"try:\n    Polynomial(degree, coeffs)\nexcept ValueError:\n    degree = len(coeffs) - 1  # self-heal only if coeffs are authoritative","preventionTips":["Always derive degree as len(coefficients) - 1.","Zero-fill missing middle powers explicitly.","Remember coefficients are ordered lowest power first."],"tags":["python","value-error","polynomial","maths","constructor"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}