Weird behavior in search in a list

Hendrik van Rooyen mail at microcorp.co.za
Fri Mar 30 02:33:18 EDT 2007


"Su Y" <s...ncn at gmail.com> wrote:

> I want find the first number in extend[] which is larger than num, so
> I wrote:
> def find(num):
>     count=0
>     for elem in extend:
>         if elem<num:
>             count+=1
>     return count
> 
> I found that if extend[] is monotonous, like [1.1, 2.3, 3.2, 4.5,
> 5.6],
> it works fine: find(4) returns 3, extend[3] is 4.5.
> But, if extend[] is not monotonous, like [1.1, 2.3, 3.2, 4.5, 5.6,
> 4.6, 3.4, 2.1, 0.3],
> find(4) returns 6, extend[6] is 3.4!
> 
> what's going on here? I really can't understand....

Hint: extend[0]  is1.1
Hint: extend[7] is 2.1
Hint: 2.1 is less than 4

You have to stop counting and come out of the loop when you find the 
first one - what your function is doing is counting the elements less than
num, not finding the first one that is.

hth - Hendrik





More information about the Python-list mailing list