Tell us what’s happening:
the error im getting “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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36
Challenge Information:
Learn Interfaces by Building an Equation Solver - Step 38
How you can test your solve()
function:
- call it in a
print()
call at the end of your code to see the output
- print the variables it uses at the top of the function
Look for any errors in the console.
Hint: Look at your __init__
method. You use the same variables there. If the variable doesn’t use self
then you cannot access it outside of that function (the __init__
function in this case)
i passed it but didn’t get the test part
i done this < print(solve(root1,root2))
What is “solve” ? What are you trying to print?
Glad you got it, but… serious doubts that you understand the code. Do you remember my example of a Class and to access skytower.boardroom
?
Let me know if you have any questions, keep at it.
no i don’t remember it, also no i don’t understand what we are meant to do, at the start i do but then i slowly forget because freecodecamp doesn’t explain it well throughout.
this is where i would use chatgpt but people have reccommended against it
Yup, we’ve been over this before.
Better off doing an Internet search, finding a resource that you like and reading all about it, or watch a video, whatever.
You will need to read other sources to supplement your learning. Revisit it as many times as you need.
I took the time to try to explain classes in the best way I could, but now you simply say that you don’t remember. How else can I help you?
This video might help you understand how to access solve, it’s 1 minute long.
https://www.youtube.com/watch?v=yYALsys-P_w
no i remember classes, i remember them well, i just don’t remember that specific one. if you gave me more detail i could probably remember it
also isn’t youtube the same thing as gpt? i don’t understand why you shouldn’t use it data scientists use it all the time for there coding
that guy explained that really well, wait so are you saying i should of just done solve() by itself? as solve only has 1 argument which is self, but then it just gives me error saying solve is not defined
Solve() is a method or function of an object. You need to access it through the object, it doesn’t exist by itself.
oh yeah, i remember that perfectly, you were talking about how the you use the self method for almost like a quick temporary name, and how it changes as the code goes.
That’s true, youtube and gpt are the same thing, I forgot about that. /sarcasm
not trying to disrespect you when i say that btw im genuinely interested on why it is frowned upon, even when used not so harmfully like explaining the purpose of code
i want to check if this is right from the explanation of the youtube video, i’ve came to this conclusion print(QuadraticEquation.solve)
good but QuadraticEquation
is a class, not an object. You create an object from the class.
solve
is a method or function, not a property so it takes (parentheses)
It’s like you’ve tried to go to the boardroom on the blueprint instead of the boardroom in a building like the music video ‘take on me’ by A-ha.
so what i also don’t understand is if the init method is called automatically with self in it, why do you need to call to def init and put self as the first argument
so this? print(quadr_eq.solve())
okay i actually do see why it’s better could i use chatgpt to refer me youtube videos? for that problem, i have a jailbroken one so i can do that im just asking is the task of searching it up perhaps a learning experience itself?