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.

102 Tuples<br />

count = 0<br />

for num in t:<br />

if low < num < high:<br />

count = count + 1<br />

print count<br />

The last step is <strong>to</strong> encapsulate this code in a function called inBucket.<br />

parameters are the list and the values low and high.<br />

The<br />

def inBucket(t, low, high):<br />

count = 0<br />

for num in t:<br />

if low < num < high:<br />

count = count + 1<br />

return count<br />

By copying and modifying an existing program, we were able <strong>to</strong> write this function<br />

quickly and save a lot of debugging time. This development plan is called pattern<br />

matching. If you find yourself working on a problem you have solved before, reuse<br />

the solution.<br />

9.7 Many buckets<br />

As the number of buckets increases, inBucket gets a little unwieldy. With two<br />

buckets, it’s not bad:<br />

low = inBucket(a, 0.0, 0.5)<br />

high = inBucket(a, 0.5, 1)<br />

But <strong>with</strong> four buckets it is getting cumbersome.<br />

bucket1 = inBucket(a, 0.0, 0.25)<br />

bucket2 = inBucket(a, 0.25, 0.5)<br />

bucket3 = inBucket(a, 0.5, 0.75)<br />

bucket4 = inBucket(a, 0.75, 1.0)<br />

There are two problems. One is that we have <strong>to</strong> make up new variable names for<br />

each result. The other is that we have <strong>to</strong> compute the range for each bucket.<br />

We’ll solve the second problem first. If the number of buckets is numBuckets, then<br />

the width of each bucket is 1.0 / numBuckets.<br />

We’ll use a loop <strong>to</strong> compute the range of each bucket. The loop variable, i, counts<br />

from 0 <strong>to</strong> numBuckets-1:

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

Saved successfully!

Ooh no, something went wrong!