[Tutor] FW: find() problem

Evert Rol evert.rol at gmail.com
Tue Aug 24 19:18:45 CEST 2010


>>> I found it.
>> 
>> Good.
>> Few generic comments nonetheless, just for the fun of it ;-).
>> 
>>> This one does the trick :
>>> 
>>> def find(strng, ch, start, step=1):
>>> index=start
>>> while 0 <= index < len(strng):
>>> if strng[index] == ch:
>>> return index 
>>> index += step
>>> return -2
>> 
>> You can actually use 'return index'. When you reach the end of the function, index == len(strng), which would be invalid in your main while condition, and the +1 would still keep it that way.
>> But read on if you want to keep the return -1 from the book.
> 
> 
> Hello Evert, 
> 
> I don't get this.
> If you reach the end of the function , index==len(string) , then this loops end. 
> index does then have the value of the last found lettter. So why +1 would it keep it that way.

In your function, you keep adding step to index. If you won't find a match for a letter anymore, index reaches len(strng) and thus you break out of the while loop. Thus you continue to the return statement, and you return index (which equals len(strng) now).
Remember that len(strng) is the length of the string, but because Python's indices are zero-based, that does *not* equal the index of the last element: fruit[len(fruit)] will give an IndexError. So index does not have the value of the last found letter (actually, it never has, because it is an index, not a letter). 
In your main while loop, now, index == len(fruit), thus the condition fails. If you add one, you would get '0 <= len(fruit)+1 < len(fruit)', (index substituted with "len(fruit)"), which just as easily fails.

But if you don't get, better not use it; that generally leads to bugs.


> 
>> 
>>> 
>>> fruit=""
>>> letter=""
>>> fruit= raw_input("Enter a sort of fruit: ")
>>> letter = raw_input("Enter the character which must be counted: ")
>>> index=1
>>> aantal=0
>>> while 0 <=index < len(fruit):
>>> x=find (fruit,letter, index)
>> 
>> You can check for x == -1 here (if you have the old find() from the book), and then break out of the loop. Provided the book has already dealt with the break statement. If you use break, your while condition can simply be 'while True:'
>> 
>>> index=x+1
>>> if x<>-2 :
> 
> I don't thought about that but it is also a possibility.
> 
>> 
>> Don't use <>, but != instead. 
>> If you ever use Python 3, it doesn't work anymore: http://docs.python.org/release/3.0.1/whatsnew/3.0.html#removed-syntax
> 
> 
> Oke,  Point taken.
> 
> 





More information about the Tutor mailing list