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.

236 Creating a new data type<br />

class Fraction:<br />

...<br />

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

diff = (self.numera<strong>to</strong>r * other.denomina<strong>to</strong>r -<br />

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

return diff<br />

If self is greater than other, thendiff will be positive. If other is greater, then<br />

diff will be negative. If they are the same, diff is zero.<br />

B.5 Taking it further<br />

Of course, we are not done. We still have <strong>to</strong> implement subtraction by overriding<br />

sub and division by overriding div .<br />

One way <strong>to</strong> handle those operations is <strong>to</strong> implement negation by overriding neg<br />

and inversion by overriding invert . Then we can subtract by negating the<br />

second operand and adding, and we can divide by inverting the second operand<br />

and multiplying.<br />

Next,wehave<strong>to</strong>provide rsub and rdiv . Unfortunately, we can’t use<br />

the same trick we used for addition and multiplication, because subtraction and<br />

division are not commutative. We can’t just set rsub and rdiv equal<br />

<strong>to</strong> sub and div . In these operations, the order of the operands makes a<br />

difference.<br />

To handle unary negation, which is the use of the minus sign <strong>with</strong> a single<br />

operand, we override neg .<br />

We can compute powers by overriding pow , but the implementation is a little<br />

tricky. If the exponent isn’t an integer, then it may not be possible <strong>to</strong> represent<br />

the result as a Fraction. For example, Fraction(2) ** Fraction(1,2) is the<br />

square root of 2, which is an irrational number (it can’t be represented as a<br />

fraction). So it’s not easy <strong>to</strong> write the most general version of pow .<br />

There is one other extension <strong>to</strong> the Fraction class that you might want <strong>to</strong> think<br />

about. So far, we have assumed that the numera<strong>to</strong>r and denomina<strong>to</strong>r are integers.<br />

As an exercise, finish the implementation of the Fraction class so that<br />

it handles subtraction, division and exponentiation.<br />

B.6 Glossary<br />

greatest common divisor (GCD): The largest positive integer that divides<br />

<strong>with</strong>out a remainder in<strong>to</strong> both the numera<strong>to</strong>r and denomina<strong>to</strong>r of a fraction.

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

Saved successfully!

Ooh no, something went wrong!