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.

9.7 Many buckets 103<br />

bucketWidth = 1.0 / numBuckets<br />

for i in range(numBuckets):<br />

low = i * bucketWidth<br />

high = low + bucketWidth<br />

print low, "<strong>to</strong>", high<br />

To compute the low end of each bucket, we multiply the loop variable by the<br />

bucket width. The high end is just a bucketWidth away.<br />

With numBuckets = 8, the output is:<br />

0.0 <strong>to</strong> 0.125<br />

0.125 <strong>to</strong> 0.25<br />

0.25 <strong>to</strong> 0.375<br />

0.375 <strong>to</strong> 0.5<br />

0.5 <strong>to</strong> 0.625<br />

0.625 <strong>to</strong> 0.75<br />

0.75 <strong>to</strong> 0.875<br />

0.875 <strong>to</strong> 1.0<br />

You can confirm that each bucket is the same width, that they don’t overlap, and<br />

that they cover the entire range from 0.0 <strong>to</strong> 1.0.<br />

Now back <strong>to</strong> the first problem. We need a way <strong>to</strong> s<strong>to</strong>re eight integers, using the<br />

loop variable <strong>to</strong> indicate one at a time. By now you should be thinking, “List!”<br />

We have <strong>to</strong> create the bucket list outside the loop, because we only want <strong>to</strong> do it<br />

once. Inside the loop, we’ll call inBucket repeatedly and update the i-eth element<br />

of the list:<br />

numBuckets = 8<br />

buckets = [0] * numBuckets<br />

bucketWidth = 1.0 / numBuckets<br />

for i in range(numBuckets):<br />

low = i * bucketWidth<br />

high = low + bucketWidth<br />

buckets[i] = inBucket(t, low, high)<br />

print buckets<br />

With a list of 1000 values, this code produces this bucket list:<br />

[138, 124, 128, 118, 130, 117, 114, 131]<br />

These numbers are fairly close <strong>to</strong> 125, which is what we expected. At least, they<br />

are close enough that we can believe the random number genera<strong>to</strong>r is working.<br />

As an exercise, test this function <strong>with</strong> some longer lists, and see if the<br />

number of values in each bucket tends <strong>to</strong> level off.

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

Saved successfully!

Ooh no, something went wrong!