#!/usr/bin/env python import math class Quadratic(object): def __init__(self, a, b, c): self._a, self._b, self._c = a, b, c for i in (a, b, c): if type(i) is not int: raise TypeError, "Only ints please." def solve(self): '''Applies the quadratic formula to the given coefficients plugged into a quadratic equation''' x = self._b**2-4*self._a*self._c if x < 0: return None # There's no real solution to this equation x = math.sqrt(x) return set((((-self._b+x)/2*self._a), ((-self._b-x)/2*self._a))) def __str__(self): '''Very sloppy way of displaying a quadratic equation given the coefficients''' return '%sx^2%s%dx%s%d' % (self._a if self._a > 1 or self._a < -1 else ('-' if self._a == -1 else ''), '+' if self._b > 0 else '', self._b, '+' if self._c > 0 else '', self._c) if __name__ == '__main__': q = Quadratic(1, 2, -8) print q print q.solve()