Learn Interfaces by Building an Equation Solver - Step 38

Tell us what’s happening:

I don’t know what’s happening or what to do. I also don’t fully understand how the quadratic formula works. Or am I doing it right?

Your code so far

from abc import ABC, abstractmethod
import re


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')
            else:
                terms.append(f"{coefficient:+}x**{n}")
        equation_string = ' '.join(terms) + ' = 0'
        return re.sub(r"(?<!\d)1(?=x)", "", 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

    def __init__(self, *args):
        super().__init__(*args)
        a, b, c = self.coefficients.values()
        self.delta = b**2 - 4 * a * c

# User Editable Region

    def solve(self):
        if self.delta < 0:
            return []
        root_1 = (-self.b + math.sqrt(self.delta)) / (2 * self.a)
        root_2 = (-self.b - math.sqrt(self.delta)) / (2 * self.a)

        return [root_1, root_2]


# User Editable Region

    def analyze(self):
        pass


lin_eq = LinearEquation(2, 3)
print(lin_eq)
quadr_eq = QuadraticEquation(11, -1, 1)
print(quadr_eq)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36

Challenge Information:

Learn Interfaces by Building an Equation Solver - Step 38

you do not have self.a and self.b available inside solve(), notice how here in __init__ they are not saved as self.
you have self.coefficients that you can use tho

Hmm, I don’t quite understand what’s wrong. I’ve tried a lot of different approaches, even unpacking the coefficients again, changing variable names, self, and adjustments to the code. But I’m still stuck here.
The console error says:

// running tests
1. Your solve method should return a list containing the correct solutions.
// tests completed

However, the preview isn’t showing any error, and I’m still using the original code I posted earlier(as none works).

Even when I try without self, it still doesn’t work:

        root1 = (-b + math.sqrt(self.delta)) / (2 * a)
        root2 = (-b - math.sqrt(self.delta)) / (2 * a)

anything that am i missing?

Hi @seopostexpert

Can you show how you defined a in the solve method?

Happy coding

hmm
image
Because that equation has it :slight_smile:

but where does it get the value inside solve?

Hmmm after a lot of trying I did a little research and imported math — and my code passed. : )
Not sure if that’s even allowed or not.

you do not need to use math to pass this step, you need to give a value to a and b

hmm so i just go back to that step and assign values?

which values tho? you can’t give it random values, you need to give it the right values

I don’t understand how math would allow you to pass tho

As importing math, idk how it was able to pass me :sweat_smile: but as i know it allow use of math.sqrt, and it passed like this. Here’s the code I used:

        a, b, c = self.coefficients.values()
        root1 = (-b + math.sqrt(self.delta)) / (2 * a)
        root2 = (-b - math.sqrt(self.delta)) / (2 * a)
        return [root1, root2]

So now should I not give a value to c? Just assign a and b only and remove c? Also, since without importing math we can’t use math.sqrt, should I remove that too? If yes, what changes should I make to the code then?

great you managed to give a value to the letters!

yeah, to use math.sqrt you need to import math, but as you can see in the next step it can be done in other ways

So, i just continue forward?

unless you have a reason to not

I got an overview after I passed and now I understand :blush: but I have one question:
Why is the _ used here?
a, b, _ = self.coefficients.values()

because the third value is not used

but still it cant work without _ like a, b =self.coefficients.values()?

you can try it, delete the underscore, what happens?

you can use QuadraticEquation(1, -7, 10) and call solve on it

I tried it, but it just won’t accept it

// running tests
1. Your solve method should return a list containing the correct solutions.
// tests completed

Also, calling it throws:
ValueError: too many values to unpack (expected 2)

so if it throws an error it doesn’t return anything

the error is why we can’t do that, Python is really precise in these things, if there are three values on the right handside of the equal sign, there must be three also on the left hand side