06.09.2021 Views

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

How to Think Like a Computer Scientist - Learning with Python, 2008a

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

234 Creating a new data type<br />

B.2 Fraction addition<br />

Addition is more complicated than multiplication, but still not <strong>to</strong>o bad. The sum<br />

of a/b and c/d is the fraction (a*d+c*b)/(b*d).<br />

Using the multiplication code as a model, we can write add and radd :<br />

class Fraction:<br />

...<br />

def __add__(self, other):<br />

if isinstance(other, int):<br />

other = Fraction(other)<br />

return Fraction(self.numera<strong>to</strong>r * other.denomina<strong>to</strong>r +<br />

self.denomina<strong>to</strong>r * other.numera<strong>to</strong>r,<br />

self.denomina<strong>to</strong>r * other.denomina<strong>to</strong>r)<br />

__radd__ = __add__<br />

We can test these methods <strong>with</strong> Fractions and integers.<br />

>>> print Fraction(5,6) + Fraction(5,6)<br />

60/36<br />

>>> print Fraction(5,6) + 3<br />

23/6<br />

>>> print 2 + Fraction(5,6)<br />

17/6<br />

The first two examples invoke add ; the last invokes radd .<br />

B.3 Euclid’s algorithm<br />

In the previous example, we computed the sum 5/6+5/6 and got 60/36. That is<br />

correct, but it’s not the best way <strong>to</strong> represent the answer. To reduce the fraction<br />

<strong>to</strong> its simplest terms, we have <strong>to</strong> divide the numera<strong>to</strong>r and denomina<strong>to</strong>r by their<br />

greatest common divisor (GCD), which is 12. The result is 5/3.<br />

In general, whenever we create a new Fraction object, we should reduce it by<br />

dividing the numera<strong>to</strong>r and denomina<strong>to</strong>r by their GCD. If the fraction is already<br />

reduced, the GCD is 1.<br />

Euclid of Alexandria (approx. 325–265 BCE) presented an algorithm <strong>to</strong> find the<br />

GCD for two integers m and n:<br />

If n divides m evenly, then n is the GCD. Otherwise the GCD is the<br />

GCD of n and the remainder of m divided by n.

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

Saved successfully!

Ooh no, something went wrong!