I am currently creating a class in python to make a quadratic equation. I wrote down a discriminant function within the class, and I'm trying to call on it within the roots function, however, I'm not sure how to do it for certain. I am getting an attribute error.
AttributeError: 'QuadraticEquation' object has no attribute 'discrimiant'
def discriminant(self):
return ((self.b)**2) - (4 * self.a * self.c)
def root1(self):
if self.discrimiant() < 0:
return None
else:
return (-self.b + math.sqrt(self.discriminant())) / (2 * self.a)
def root2(self):
if self.discrimiant() < 0:
return None
else:
return (-self.b - math.sqrt(self.discriminant())) / (2 * self.a)
There is a spelling mistake in your code. discriminant, not discrimiant. Here is a working code -
class QuadraticEquation:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def discriminant(self):
return ((self.b)**2) - (4 * self.a * self.c)
def root1(self):
if self.discriminant() < 0:
return None
else:
return (-self.b + math.sqrt(self.discriminant())) / (2 * self.a)
def root2(self):
if self.discriminant() < 0:
return None
else:
return (-self.b - math.sqrt(self.discriminant())) / (2 * self.a)
a = QuadraticEquation(1,2,3)
print a.root1()
print a.root2()
print a.discriminant()
Related
I tried to implement fractions using classes in python, but when I ran it,
it showed the error 'function gcd is not defined'. I can't seem to figure out how.
However, when I defined GCD outside the class it was working perfectly fine.
class frac:
def gcd(a, b):
if(b == 0):
return a
else:
return gcd(b, a%b)
def __init__(self, numer, denom):
if(denom == 0):
raise Exception("WTF")
else:
self.numer = numer
self.denom = denom
self.ratify()
def ratify(self):
g = gcd(self.numer, self.denom)
self.numer = self.numer/g
self.denom = self.denom/g
def add(self, b):
n,d = self.numer, self.denom
self.numer = n*b.denom + d*b.numer
self.denom = d*b.denom
self.ratify()
What is going wrong?
Your gcd method needs to look like:
def gcd(self, a, b):
if(b == 0):
return a
else:
return self.gcd(b, a%b)
I've been attempting to complete one of my subjects for the OOP, but I couldn't manage to figure out what's wrong with the definition of my functions. I'm a newbie in this language, already searched the forums but I couldn't find anything useful.
Error message:
Traceback (most recent call last):
File "/home/main.py", line 44, in
add(x, y)
NameError: name 'add' is not defined
This is the program I wrote.
class Complex(object):
def __init__(self, r = 0, i = 0):
self.r = r
self.i = i
def __str__ (self):
return "%s + i%s" % (self.r, self.i)
def add (self, other):
summ = Complex()
summ.r = self.r + other.r
summ.i = self.i + other.i
return "Sum is %d" % summ
def dif (self, other):
dif = Complex()
dif.r = self.r - other.r
dif.i = self.i - other.i
return dif
def multiply (self, other):
multiply = Complex()
multiply.r = self.r * other.r
multiply.i = self.i * other.i
return "%d" % (-1 * multiply.r * multiply.i)
def divide (self, other):
divide = Complex()
divide.r = self.r / other.r
divide.i = self.i / other.i
return "%d" % (divide.r / divide.i)
x = Complex()
y = Complex()
x.r = int(input("Type in real part of x: \n"))
x.i = int(input("Type in imaginary of x: \n"))
print (x, "\n")
y.r = int(input("Type in real part of y: \n"))
y.i = int(input("Type in imaginary of y: \n"))
print (y, "\n")
add(x, y)
The add() function is a member of the Complex class but you are calling it on its own.
You need to call it like this
x.add(y)
When a function is a member of a class like below:
class Complex(object):
def add (self, other):
# Do stuff
The object the function is called on automatically gets passed as self.
So if you call x.add(y), self will be x and other will be y.
If add is a method of your class Complex, then you must write x.add(y) instead of add(x, y).
I know that it is confusing in Python. You need always to apply the "self" as first argument of a method, although it is not an argument, but the object whose method you call.
Using pycharm, I wish to refactor methods into a class. (Staticmethod would do)
Current:
import math
class Solver(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def demo(b, a, c):
d = b ** 2 - 4 * a * c
if d >= 0:
disc = math.sqrt(d)
root1 = (- b + disc) / (2 * a)
root2 = (- b - disc) / (2 * a)
print(root1, root2)
return root1, root2
else:
raise Exception
s = Solver(2, 123, 0.025)
demo(s.b, s.a, s.c)
Desired:
import math
class Solver(object):
def __init__(self,a,b,c):
self.a = a
self.b = b
self.c = c
def demo(self, a, b, c):
d = self.b ** 2 - 4 * self.a * self.c
if d >= 0:
disc = math.sqrt(d)
root1 = (- self.b + disc) / (2 * self.a)
root2 = (- self.b - disc) / (2 * self.a)
print(root1, root2)
return root1, root2
else:
raise Exception
Solver(2, 123, 0.025).demo()
I am basically trying to get the opposite functionality to:
"Moving function/method to the top-level"
as described here:
https://www.jetbrains.com/help/pycharm/2017.1/move-refactorings.html
I wouldn't mind on settling for a class with no init params.
By default there is no such option: PyCharm is quite good at refactoring classes and methods, but can't do much with standalone functions.
Though, there is a solution for your problem: regex!
Basically, what you have to do is:
Change function to bounded method (you already did that in your example)
Replace all occurrences of old method call with refactored one.
Here is the regex which would let you do that for aforementioned example:
([\w]+)[ \t]+=[ \t](Solver[ \t]*\(([\d.]+)[ \t]*,[ \t]*([\d.]+)[ \t]*,[ \t]*([\d.]+)[ \t]*\))\n\r?demo[ \t]*\(\1\.b[ \t]*,[ \t]*\1\.a[ \t]*,[ \t]*\1\.c[ \t]*\)
And here is the replacement:
$2\.demo()
Now you can select Edit -> Find -> Replace in Path in PyCharm, check regex option, paste first regex to first field and second to next one. I've tested that locally with one file and it worked well. And here is regex101 example so you can play with it and test it.
This would be useful if you have a lot of usages of that method, otherwise it could be faster to do that manually.
I tried to add a pgdc function in the Fraction class in order to calculate the biggest common divided or a number pgdc ... The function should be recursive. However, I keep getting the following error:
Traceback (most recent call last):
File "C:/Users/jf/Desktop/Python-jEdit_v2/23_fraction.py", line 60, in <module>
p = a.plus(b)
File "C:/Users/jf/Desktop/Python-jEdit_v2/23_fraction.py", line 35, in plus
return resultat.simplifier()
File "C:/Users/jf/Desktop/Python-jEdit_v2/23_fraction.py", line 27, in simplifier
p = pgcd(self.num, self.den)
NameError: global name 'pgcd' is not defined
In addition,
I also got the following error for the simplifier : AttributeError: Fraction instance has no attribute 'simplifier'
Which, leave me puzzle, as I tried to add self.pgcd=pgcd and self.simplifier=simplifier
at various places and it still did not work well...
# -*- coding: utf-8 -*-
class Fraction():
# constructeur et attributs
def __init__(self, num = 0, den = 1):
self.num = num
if (den == 0):
erreur("Dénominateur nul") #fonction d'erreur
self.den = den
def __str__(self):
return str(self.num) + "/" + str(self.den)
def erreur(message):
print "Erreur: " + message
from sys import exit
exit()
def pgcd(a, b):
if a == b:
return a
if a > b:
return pgcd(a-b, b)
else:
return pgcd(a, b-a)
def simplifier(self):
p = pgcd(self.num, self.den)
self.num = self.num / p
self.den = self.den / p
return self
def plus(self, f):
resultat = Fraction(self.num * f.den + self.den * f.num, \
self.den * f.den)
return resultat.simplifier()
def moins(self, f):
resultat = Fraction(self.num * f.den - self.den * f.num, \
self.den * f.den)
if (resultat.num < 0):
# changer de signe avant de simplifier
resultat.num = - resultat.num
resultat = resultat.simplifier()
resultat.num = - resultat.num
return resultat
else:
return resultat.simplifier()
def fois(self, f):
resultat = Fraction(self.num * f.num, self.den * f.den)
return resultat.simplifier()
def div(self, f):
resultat = Fraction(self.num * f.den, self.den * f.num)
return resultat.simplifier()
#### CONSOLE ####
a = Fraction(5, 11)
b = Fraction(3, 7)
p = a.plus(b)
You need to declare self as a parameter of your function and use it when you want to recursively call pgcd:
def pgcd(self,a, b):
if a == b:
return a
if a > b:
return self.pgcd(a-b, b)
else:
return self.pgcd(a, b-a)
Also, call pgcd with self. on this line:
p = self.pgcd(self.num, self.den) #from pgcd(self.num, self.den)
I have the following code:
class Quadratic:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def function(self, x):
self.F(x) = a*(x**2) + b*x + c
return F(x)
def table(self, lower, upper, varz):
inc = np.absolute(upper-lower) / varz
print inc
for i in range(0 , varz - 1):
self.F(lower)
lower = lower + inc
#lower bound,upper bound, number of values
def roots():
x1 = (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)
x2 = (-b - math.sqrt(b**2 - 4*a*c)) / (2*a)
return x1, x2
def dump(self):
print self.n
Whenever I try and run this script, I get the following:
line 15
self.F(x) = a*(x**2) + b*x + c
SyntaxError: can't assign to function call
Any help or ideas would be greatly appreciated.
It is not clear (to me at least) what it is you're trying to achieve, but perhaps it is as simple as this:
def F(self, x):
return self.a * (x ** 2) + self.b * x + c
As you might have guessed, F(x) is a function call. You're calling the function F, which does not actually exist, passing it the argument x, which does not actually exist either. You need to give your variables legal names, like f_of_x.
try with:
def __init__(self, a,b,c):
self.a = a
self.b = b
self.c = c
self.F = lambda x: a*(x**2)+b*x+c
and discard the function() method