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

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

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

10.6 Long integers 113<br />

Using this version of fibonacci, our machines can compute fibonacci(40) in<br />

an eyeblink. But when we try <strong>to</strong> compute fibonacci(50), weseethefollowing:<br />

>>> fibonacci(50)<br />

20365011074L<br />

The L at the end of the result indicates that the answer +(20,365,011,074) is <strong>to</strong>o<br />

big <strong>to</strong> fit in<strong>to</strong> a <strong>Python</strong> integer. <strong>Python</strong> has au<strong>to</strong>matically converted the result <strong>to</strong><br />

a long integer.<br />

10.6 Long integers<br />

<strong>Python</strong> provides a type called long that can handle any size integer. There are<br />

twoways<strong>to</strong>createalong value. One is <strong>to</strong> write an integer <strong>with</strong> a capital L at<br />

the end:<br />

>>> type(1L)<br />

<br />

The other is <strong>to</strong> use the long function <strong>to</strong> convert a value <strong>to</strong> a long. long can<br />

accept any numerical type and even strings of digits:<br />

>>> long(1)<br />

1L<br />

>>> long(3.9)<br />

3L<br />

>>> long(’57’)<br />

57L<br />

All of the math operations work on longs, so in general any code that works <strong>with</strong><br />

integers will also work <strong>with</strong> long integers. Any time the result of a computation is<br />

<strong>to</strong>o big <strong>to</strong> be represented <strong>with</strong> an integer, <strong>Python</strong> detects the overflow and returns<br />

the result as a long integer. For example:<br />

>>> 1000 * 1000<br />

1000000<br />

>>> 100000 * 100000<br />

10000000000L<br />

Inthefirstcasetheresulthastypeint; in the second case it is long.<br />

10.7 Counting letters<br />

In Chapter 7, we wrote a function that counted the number of occurrences of a<br />

letter in a string. A more general version of this problem is <strong>to</strong> form a his<strong>to</strong>gram

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

Saved successfully!

Ooh no, something went wrong!