curriculum/challenges/english/blocks/learn-interfaces-by-building-an-equation-solver/663a22ba7420c4d2f7fd2aec.md
It's time to implement the solve method. Given a linear equation in the form \( ax + b = 0 \), the solution is \(x = -\frac{b}{a}\).
Unpack the coefficients stored in the coefficients attribute into the variables a and b. Note that you'll need to use the .values() method.
Then, declare a variable x, assign it the solution of the equation and return it from the solve method.
You should unpack the values stored inside the coefficients attribute into the variables a and b.
({ test: () => assert(runPython(`_Node(_code).find_class("LinearEquation").find_function("solve").has_stmt("a, b = self.coefficients.values()")`)) })
You should declare a variable named x and assign it the solution of the linear equation.
({ test: () => assert(runPython(`_Node(_code).find_class("LinearEquation").find_function("solve").has_stmt("x = -b/a")`)) })
You should return x from your solve method.
({ test: () => assert(runPython(`_Node(_code).find_class("LinearEquation").find_function("solve").has_return("x")`)) })
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
--fcc-editable-region--
def solve(self):
pass
--fcc-editable-region--
def analyze(self):
pass
lin_eq = LinearEquation(2, 3)
print(lin_eq)