Skip to main content

Section 7.19 A find function

Here is an implementation for a restricted find method, where the target is a single character.
In a sense, find is the opposite of the indexing operator. Instead of taking an index and extracting the corresponding character, it takes a character and finds the index where that character appears for the first time. If the character is not found, the function returns -1.
The while loop in this example uses a slightly more complex condition than we have seen in previous programs. Here there are two parts to the condition. We want to keep going if there are more characters to look through and we want to keep going if we have not found what we are looking for. The variable found is a boolean variable that keeps track of whether we have found the character we are searching for. It is initialized to False. If we find the character, we reassign found to True.
The other part of the condition is the same as we used previously to traverse the characters of the string. Since we have now combined these two parts with a logical and, it is necessary for them both to be True to continue iterating. If one part fails, the condition fails and the iteration stops.
When the iteration stops, we must ask a question to find out the individual condition that caused the termination, and then return the proper value. This is a pattern for dealing with while loops with compound conditions.

Note 7.19.1.

This pattern of computation is sometimes called a eureka traversal because as soon as we find what we are looking for, we can cry “Eureka!” and stop looking. The way we stop looking is by setting found to True, which causes the condition to fail.

Checkpoint 7.19.2.

For more practice with while and compound conditions, rewrite the count function from the previous page so that the second parameter can be a multi-character string. Thus, count("banana", "an") would return 2. A call like this: count("gooogle", "oo") should return 1; the middle “o” is not counted twice. You will probably want to use slices in your solution.