30.11.2014 Views

A4 portrait - PET: Python Entre Todos - Python Argentina

A4 portrait - PET: Python Entre Todos - Python Argentina

A4 portrait - PET: Python Entre Todos - Python Argentina

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

How should the test be? 16<br />

raise NotQuadratic()<br />

discriminant = b * b - 4 * a * c<br />

if discriminant < 0:<br />

raise NoRealRoots()<br />

root_discriminant = math.sqrt(discriminant)<br />

first_root = (-1 * b + root_discriminant) / (2 * a)<br />

second_root = (-1 * b - root_discriminant) / (2 * a)<br />

# min y max are python functions<br />

chico = min(first_root, second_root)<br />

grande = max(first_root, second_root)<br />

return (chico, grande)<br />

def find_coefficients(first_root, second_root):<br />

"""Given the roots of a quadratic function, return the coefficients.<br />

The quadratic function is given by:<br />

(x - r1) * (x - r2) = 0<br />

"""<br />

# You can reach this result by applying distribution<br />

return (1, -1 * (first_root + second_root), first_root * second_root)<br />

Finally, let’s see the tests we wrote for that code:<br />

import unittest<br />

from polynomial import find_roots, find_coefficients, \<br />

NotQuadratic, NoRealRoots<br />

class Testpolynomial(unittest.TestCase):<br />

def test_find_roots(self):<br />

COEFFICIENTS_ROOTS = [<br />

((1,0,0), (0, 0)),<br />

((-1,1,2), (-1, 2)),<br />

((-1,0,4), (-2, 2)),<br />

]<br />

for coef, expected_roots in COEFFICIENTS_ROOTS:<br />

roots = find_roots(coef[0], coef[1], coef[2])<br />

self.assertEquals(roots, expected_roots)<br />

def test_form_polynomial(self):<br />

RAICES_COEFFICIENTS = [<br />

((1, 1), (1, -2, 1)),<br />

((0, 0), (1, 0, 0)),<br />

((2, -2), (1, 0, -4)),<br />

((-4, 3), (1, 1, -12)),<br />

]<br />

for roots, expected_coefficients in RAICES_COEFFICIENTS:<br />

coefficients = find_coefficients(roots[0], roots[1])<br />

self.assertEquals(coefficients, expected_coefficients)<br />

def test_cant_find_roots(self):<br />

self.assertRaises(NoRealRoots, find_roots, 1, 0, 4)<br />

def test_not_quadratic(self):<br />

self.assertRaises(NotQuadratic, find_roots, 0, 2, 3)<br />

<strong>PET</strong>: English Translation (Issue 1, August 2010) — http://revista.python.org.ar

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!