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.

78 Strings<br />

7.7 A find function<br />

What does the following function do?<br />

def find(str, ch):<br />

index = 0<br />

while index < len(str):<br />

if str[index] == ch:<br />

return index<br />

index = index + 1<br />

return -1<br />

Inasense,find is the opposite of the [] opera<strong>to</strong>r. Instead of taking an index and<br />

extracting the corresponding character, it takes a character and finds the index<br />

where that character appears. If the character is not found, the function returns<br />

-1.<br />

This is the first example we have seen of a return statement inside a loop. If<br />

str[index] == ch, the function returns immediately, breaking out of the loop<br />

prematurely.<br />

If the character doesn’t appear in the string, then the program exits the loop<br />

normally and returns -1.<br />

This pattern of computation is sometimes called a “eureka” traversal because as<br />

soon as we find what we are looking for, we can cry “Eureka!” and s<strong>to</strong>p looking.<br />

As an exercise, modify the find function so that it has a third parameter,<br />

the index in the string where it should start looking.<br />

7.8 Looping and counting<br />

The following program counts the number of times the letter a appears in a string:<br />

fruit = "banana"<br />

count = 0<br />

for char in fruit:<br />

if char == ’a’:<br />

count = count + 1<br />

print count<br />

This program demonstrates another pattern of computation called a counter.<br />

The variable count is initialized <strong>to</strong> 0 and then incremented each time an a is<br />

found. (To increment is <strong>to</strong> increase by one; it is the opposite of decrement,<br />

and unrelated <strong>to</strong> “excrement,” which is a noun.) When the loop exits, count<br />

contains the result—the <strong>to</strong>tal number of a’s.

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

Saved successfully!

Ooh no, something went wrong!