curriculum/challenges/english/blocks/learn-interfaces-by-building-an-equation-solver/663b83a28943e6aa6275a514.md
Still within the Equation class, define a __str__ method to give a proper string representation to the equation objects you are going to create.
For now, within the __str__ method, declare a variable terms and assign it an empty list. You'll use this variable to store each term (coefficient times \( x^n \)) of your equation.
Then, declare a variable equation_string, assign it the result of joining the elements in the terms list with a space. Finally, return equation_string.
You should define a __str__ method within the Equation class.
({ test: () => assert(runPython(`_Node(_code).find_class("Equation").has_function("__str__")`)) })
Your __str__ method should take one parameter, self.
({ test: () => assert(runPython(`_Node(_code).find_class("Equation").find_function("__str__").has_args("self")`)) })
You should declare a variable terms and assign it an empty list within the __str__ method.
({ test: () => assert(runPython(`_Node(_code).find_class("Equation").find_function("__str__").has_stmt("terms = []")`)) })
You should declare a variable equation_string and assign it the result of joining the elements in terms with a space within the __str__ method.
({ test: () => assert(runPython(`_Node(_code).find_class("Equation").find_function("__str__").has_stmt("equation_string = ' '.join(terms)")`)) })
You should return equation_string from your __str__ method.
({ test: () => assert(runPython(`_Node(_code).find_class("Equation").find_function("__str__").has_return("equation_string")`)) })
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")
self.coefficients = {(len(args) - n - 1): arg for n, arg in enumerate(args)}
def __init_subclass__(cls):
if not hasattr(cls, "degree"):
raise AttributeError(
f"Cannot create '{cls.__name__}' class: missing required attribute 'degree'"
)
--fcc-editable-region--
--fcc-editable-region--
@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)
print(lin_eq)