Back to Freecodecamp

Step 13

curriculum/challenges/english/blocks/learn-interfaces-by-building-an-equation-solver/662fbcef5f05e1b84f541a0c.md

latest2.7 KB
Original Source

--description--

Each equation object will be instantiated passing as many arguments as the coefficients of the equation, starting from n-th degree of \( x \) down to the zero-th degree, including the possible coefficient with the value of 0.

For example, LinearEquation(4, 5) would represent the equation \( 4x + 5 = 0 \), with 4 being the coefficient of the first (highest here) degree and 5 the coefficient of the zero-th degree.

You need to check that the right number of arguments is passed to instantiate the equation object.

Inside the __init__ method, create an if statement to check if the length of args is different from the number of coefficients the equation should have (degree + 1). If it is, raise a TypeError and use the following string to provide a custom message: f"'{self.__class__.__name__}' object takes {self.degree + 1} positional arguments but {len(args)} were given".

Then, fix the error by passing the 2 and 3 to instantiate lin_eq.

--hints--

You should create an if statement that checks if the number of coefficients used to instantiate the equation is different from degree + 1.

js
({ test: () => assert(runPython(`
cond = _Node(_code).find_class("Equation").find_function("__init__").find_ifs()[0].find_conditions()[0]
cond.is_equivalent("(self.degree + 1) != len(args)") or cond.is_equivalent("len(args) != (self.degree + 1)")
`)) })

You should raise a TypeError within the new if statement and use the provided string to return a custom error message.

js
({ test: () => assert(runPython(`_Node(_code).find_class("Equation").find_function("__init__").find_ifs()[0].find_bodies()[0].has_stmt('raise TypeError(f"\\'{self.__class__.__name__}\\' object takes {self.degree + 1} positional arguments but {len(args)} were given")')
`)) })

You should pass 2 and 3 to instantiate lin_eq.

js
({ test: () => assert(runPython(`_Node(_code).has_stmt("lin_eq = LinearEquation(2, 3)")`)) })

--seed--

--seed-contents--

py
from abc import ABC, abstractmethod

class Equation(ABC):
    degree: int
--fcc-editable-region--
    def __init__(self, *args):
        pass        
    
    def __init_subclass__(cls):
        if not hasattr(cls, "degree"):
            raise AttributeError(
                f"Cannot create '{cls.__name__}' class: missing required attribute 'degree'"
            )
    
    @abstractmethod
    def solve(self):
        pass
        
    @abstractmethod
    def analyze(self):
        pass
        
class LinearEquation(Equation):
    degree = 1
    
    def solve(self):
        pass
    
    def analyze(self):
        pass
    
lin_eq = LinearEquation()
--fcc-editable-region--