Back to Freecodecamp

Step 17

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

latest2.8 KB
Original Source

--description--

After validating the coefficients, you need to store them in an instance attribute. Use a dictionary comprehension to create a dictionary in which the key is the degree of the coefficient and the corresponding value is the coefficient, and assign it to an attribute named coefficients.

For example, a LinearEquation object instantiated with 2 and 4 should have the following coefficients attribute: {1: 2, 0: 4}, because 2 corresponds to the first degree of x and 4 corresponds to zero-th degree of x.

Create the key-value pairs in your new dictionary following the same order as in args.

--hints--

You should declare an attribute named coefficients within your __init__ method.

js
({ test: () => assert(runPython(`_Node(_code).find_class("Equation").find_function("__init__").has_variable("self.coefficients")`)) })

You should use a dictionary comprehension to store your coefficients.

js
({ test: () => runPython(`
import ast
node = _Node(_code).find_class("Equation").find_function("__init__").find_variable("self.coefficients")
assert isinstance(node.tree.value, ast.DictComp)
`) })

Your coefficients attribute should be a dictionary containing key-value pairs in the form degree-coefficient. Remember to follow the same order in which coefficients are stored inside args.

js
({ test: () => runPython(`
actual1 = list(LinearEquation(1, 6).coefficients.items())
expected1 = list({1: 1, 0: 6}.items())
actual2 = list(LinearEquation(-3.5, 0).coefficients.items())
expected2 = list({1: -3.5, 0: 0}.items())
assert actual1 == expected1
assert actual2 == expected2
`) })

--seed--

--seed-contents--

py
from abc import ABC, abstractmethod

class Equation(ABC):
    degree: int
    
    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'")
        if args[0] == 0:
            raise ValueError("Highest degree coefficient must be different from zero")
--fcc-editable-region--
        
--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)