#!/usr/bin/python
# Criado em:Dom 12/Ago/2007 hs 10:49
# Last Change: Dom 12 Ago 2007 11:11:06 BRT
# Instituicao:
import math
class Raizes:
def __init__(self, a, b, c): #construtores
self.a = a
self.b = b
self.c = c
self.delta = self.b**2 - 4 * self.a * self.c
def calcula_Raizes(self): #metodo_de_calculo_das_raizes
if self.delta < 0:
print "Delta negativo:ndelta: %f" %(self.delta)
elif self.delta == 0:
self.xxx = (-self.b + math.sqrt(self.delta)) / 2*self.a
print "Valor Calculado.nx: %fndelta: %f" %(self.xxx, self.delta)
elif self.delta > 0:
self.x = (-self.b + math.sqrt(self.delta)) / 2*self.a
self.xx = (-self.b - math.sqrt(self.delta)) / 2*self.a
print "Raizes.nx: %fnxx: %fndelta: %f" %(self.x, self.xx, self.delta)
Refactorings
No refactoring yet !
frangossauro
October 28, 2009, October 28, 2009 18:02, permalink
Please, post in english, since this site is international. I'm brazilian also, but it's better
to just post in english. Thanks bro.
Your code does the job, but seems to me an overkill to create a class just to do some basic computation. Beware, do not use class in everything just to look cool. They have a purpose.
The second problem is that your code does TOO MUCH. The best classes over there just do an
function, and does it well. It will not print, it will not log things, it will not save to
file (except this is the documented and expected behaviour). It's better that you just do
one thing, and do it well (in that case, computing second degree roots of quadratic equations). Just
let the top-level code do the correct behaviour (printing on the screen, saying that the equation
is wrong, and so on).
This is my implementation...
#!/usr/bin/python
# encoding: utf-8
from math import sqrt
from sys import argv
def find_quadraticRoots( a,b,c ):
delta = b**2 - (4*a*c)
root1 = root2 = 0
if delta < 0:
raise ValueError("No real root found.")
else:
root1 = root2 = (-b + sqrt(delta)) / 2*a
if delta > 0:
root2 = (-b - sqrt(delta)) / 2*a
return (root1, root2)
if __name__ == "__main__":
try:
(root1,root2) = find_quadraticRoots( int(argv[1]), int(argv[2]), int(argv[3]) )
print "Root's found: %s" % (root1 == root2 and str(root1) or str(root1) + " , " + str(root2))
except ValueError:
print "Oh my good, delta is negative. There is no REAL root!"
except IndexError:
print "Usage: %s a b c" % argv[0]
Equação do segundo graum em python