curriculum/challenges/english/blocks/learn-interfaces-by-building-an-equation-solver/664e4a590b52ba8d2adff19f.md
The discriminant of a quadratic equation in the form \( ax^2 + bx + c = 0 \), usually indicated by the capital Greek letter delta, is equal to \( Δ = b^2 - 4ac \).
Within the QuadraticEquation class, define an __init__ method. Use super() to call the __init__ method from the parent class. Then, define a new attribute named delta, which stores the value of the discriminant of the equation.
You should define an __init__ method within the QuadraticEquation class.
({ test: () => assert(runPython(`_Node(_code).find_class("QuadraticEquation").has_function("__init__")`)) })
Your __init__ method should take two parameters, self and *args.
({ test: () => assert(runPython(`_Node(_code).find_class("QuadraticEquation").find_function("__init__").has_args("self, *args")`)) })
You should call super().__init__(*args) within your __init__ method.
({ test: () => assert(runPython(`_Node(_code).find_class("QuadraticEquation").find_function("__init__").has_call("super().__init__(*args)")`)) })
You should declare a delta attribute within your __init__ method and assign it the value of the discriminant of the equation.
({ test: () => runPython(`
eq = QuadraticEquation(2, -3, -4)
assert eq.delta == 41
`) })
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'"
)
def __str__(self):
terms = []
for n, coefficient in self.coefficients.items():
if not coefficient:
continue
if n == 0:
terms.append(f'{coefficient:+}')
elif n == 1:
terms.append(f'{coefficient:+}x')
equation_string = ' '.join(terms) + ' = 0'
return equation_string.strip('+')
@abstractmethod
def solve(self):
pass
@abstractmethod
def analyze(self):
pass
class LinearEquation(Equation):
degree = 1
def solve(self):
a, b = self.coefficients.values()
x = -b / a
return x
def analyze(self):
slope, intercept = self.coefficients.values()
return {'slope': slope, 'intercept': intercept}
class QuadraticEquation(Equation):
degree = 2
--fcc-editable-region--
--fcc-editable-region--
def solve(self):
pass
def analyze(self):
pass
lin_eq = LinearEquation(2, 3)
print(lin_eq)