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.

B.4 Comparing fractions 235<br />

This recursive definition can be expressed concisely as a function:<br />

def gcd (m, n):<br />

if m % n == 0:<br />

return n<br />

else:<br />

return gcd(n, m%n)<br />

In the first line of the body, we use the modulus opera<strong>to</strong>r <strong>to</strong> check divisibility. On<br />

the last line, we use it <strong>to</strong> compute the remainder after division.<br />

Since all the operations we’ve written create new Fractions for the result, we can<br />

reduce all results by modifying the initialization method.<br />

class Fraction:<br />

def __init__(self, numera<strong>to</strong>r, denomina<strong>to</strong>r=1):<br />

g = gcd (numera<strong>to</strong>r, denomina<strong>to</strong>r)<br />

self.numera<strong>to</strong>r = numera<strong>to</strong>r / g<br />

self.denomina<strong>to</strong>r = denomina<strong>to</strong>r / g<br />

Now whenever we create a Fraction, it is reduced <strong>to</strong> its simplest form:<br />

>>> Fraction(100,-36)<br />

-25/9<br />

A nice feature of gcd is that if the fraction is negative, the minus sign is always<br />

moved <strong>to</strong> the numera<strong>to</strong>r.<br />

B.4 Comparing fractions<br />

Suppose we have two Fraction objects, a and b, and we evaluate a == b. The<br />

default implementation of == tests for shallow equality, so it only returns true if<br />

a and b are the same object.<br />

More likely, we want <strong>to</strong> return true if a and b have the same value—that is, deep<br />

equality.<br />

We have <strong>to</strong> teach fractions how <strong>to</strong> compare themselves. As we saw in Section 15.4,<br />

we can overload all the comparison opera<strong>to</strong>rs at once by supplying a cmp<br />

method.<br />

By convention, the cmp method returns a negative number if self is less than<br />

other, zero if they are the same, and a positive number if self is greater than<br />

other.<br />

The simplest way <strong>to</strong> compare fractions is <strong>to</strong> cross-multiply. If a/b > c/d, then<br />

ad>bc. With that in mind, here is the code for cmp :

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

Saved successfully!

Ooh no, something went wrong!