Learn Interfaces by Building an Equation Solver - Step 38

Tell us what’s happening:

Not able to understand what is wrong in the code. I am really stuck on this one. Please help me understand where am I going wrong?
The hint is: Your solve method should return a list containing the correct solutions.’

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 []
        root1 = (-b + (self.delta**0.5)) / (2 * a)  
        root2 = (-b - (self.delta**0.5)) / (2 * a) 
        return [root1,root2]

# 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/137.0.0.0 Safari/537.36 Edg/137.0.0.0

Challenge Information:

Learn Interfaces by Building an Equation Solver - Step 38

1 Like

Could you explain what are the variables like a, b, or self.delta?

Hi! You’re very close. Here are a few hints that can help you out. The variables are defined as local variables in __init__. Does that seem correct to you? Think in terms of instance variables instead.

Next, in the solve method, these variables are being used, but they are not instance variables. Fixing the variable type initialization from local to instance variables, and then making the respective changes, should fix the problem. Good luck!

I am not able to understand where I went wrong. It is getting very frustrating.
Help me out please!

Even when I used this code, it still does not work:

def solve(self):
    if self.delta < 0:
        return []
    root1 = (-self.b + self.delta) / (2 * self.a)
    root1 = (-self.b - self.delta) / (2 * self.a)
        
    return [root1, root2]

Can’t do this, because it’s part of the seed code.

@shivanshsharma30001 What @smit_007 says is correct though, a and b are local function variables, and you cannot access them from this new function unless you re-initialize them as new local function variables.

I have to define them again in the solve function, so that I can access them, right?

1 Like

Makes sense, you should try it and see

Yes, it works. Thank you!

Just by adding this line of code: removed by moderator

1 Like

Glad you got it, please don’t add solution code to the forum though, thanks

Awesome! Glad to hear that worked!