Sorting: too different times. Why?

Duncan Booth duncan.booth at invalid.invalid
Sun Nov 22 12:06:56 CET 2009


n00m <n00m at narod.ru> wrote:

> Any comment:
> 
> class Vector:
>     def __init__(self, x, y):
>         self.x = x
>         self.y = y
>     def __cmp__(self, v):
>         if self.x < v.x and self.y > v.y:
>             return -1
>         return 0
> 
> def v_cmp(v1, v2):
>     if v1.x < v2.x and v1.y > v2.y:
>         return -1
>     return 0

What's that comparison function supposed to be doing?

>>> print Vector(1, 1) < Vector(2, 0)
True
>>> print Vector(2, 0) == Vector(1, 1)
True

If you use a broken comparison function then you must expect strange 
results, and your list of vectors isn't going to end up in any particular 
order (try adding "c.reverse()" before the call to "c.sort()" and the two 
'sorted' lists won't match any more).

In this case though the time difference may simply be down to creating in 
excess of 1 million bound methods.



More information about the Python-list mailing list