Weird behavior in search in a list

Amit Khemka khemkaamit at gmail.com
Thu Mar 29 14:15:22 CEST 2007


On 29 Mar 2007 04:51:00 -0700, Su Y <suyuancn at gmail.com> wrote:
> hi all,
> I can't understand how this code work, its behavior is really weird
> for me...
>
> 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....

Actually your function "find" returns the number of elements in list
extend, which are smaller than the argument. Perhaps you wanted to
'break' when once the condition is met.

 def find(num):
     count=0
     for elem in extend:
         if elem>num: break
         else: count+=1
     return count

Btw a concise way could be:
def getfirstbigger(num):
    for i,x in enumerate(extend):
        if x>num:    return i
    return len(extend)

HTH,


-- 
----
Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.



More information about the Python-list mailing list