Back to Freecodecamp

Step 16

curriculum/challenges/english/blocks/learn-interfaces-by-building-an-equation-solver/6639f947d3a1818c9322c64a.md

latest2.2 KB
Original Source

--description--

The last step of validating the coefficients is checking that the highest degree coefficient is different from zero. Remember that the highest degree coefficient should be passed as the first argument when instantiating the object.

Add an if statement for that and raise a ValueError using the following string to provide a custom message: 'Highest degree coefficient must be different from zero'.

--hints--

You should create an if statement that checks if the first coefficient passed to instantiate the equation is equal to zero.

js
({ test: () => assert(runPython(`
cond = _Node(_code).find_class("Equation").find_function("__init__").find_ifs()[2].find_conditions()[0]
cond.is_equivalent("args[0] == 0") or cond.is_equivalent("0 == args[0]") or cond.is_equivalent("not args[0]")
`)) })

You should raise a ValueError 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()[2].find_bodies()[0].has_stmt("raise ValueError('Highest degree coefficient must be different from zero')")
`)) })

--seed--

--seed-contents--

py
from abc import ABC, abstractmethod

class Equation(ABC):
    degree: int
--fcc-editable-region--
    def __init__(self, *args):
        if (self.degree + 1) != len(args):
            raise TypeError(
                f"'Equation' object takes {self.degree + 1} positional arguments but {len(args)} were given"
            )
        if any(not isinstance(arg, (int, float)) for arg in args):
            raise TypeError("Coefficients must be of type 'int' or 'float'")
--fcc-editable-region--
    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(2, 3)