[Tutor] [newbie alert] why can't I find a function that gives me the sign of an integer?

Orri Ganel singingxduck at gmail.com
Thu Jan 26 21:15:27 CET 2006


No problem.  As for the main use of  cmp(), btw, afaik, it's used to 
define custom sorting, as in the following:

 >>> import random
 >>> temp = []
 >>> for i in range(10):
    
temp.append((random.randint(0,100),random.randint(0,100),random.randint(0,100)))

   
 >>> temp
[(16, 70, 87), (57, 80, 33), (14, 22, 2), (21, 92, 69), (40, 18, 90), 
(60, 78, 35), (3, 98, 7), (32, 21, 39), (15, 67, 15), (70, 95, 39)]
 >>> temp.sort(cmp=lambda x, y: cmp(x[0],y[0]))
 >>> temp
[(3, 98, 7), (14, 22, 2), (15, 67, 15), (16, 70, 87), (21, 92, 69), (32, 
21, 39), (40, 18, 90), (57, 80, 33), (60, 78, 35), (70, 95, 39)]
 >>> temp.sort(cmp=lambda x, y: cmp(x[1],y[1]))
 >>> temp
[(40, 18, 90), (32, 21, 39), (14, 22, 2), (15, 67, 15), (16, 70, 87), 
(60, 78, 35), (57, 80, 33), (21, 92, 69), (70, 95, 39), (3, 98, 7)]
 >>> temp.sort(cmp=lambda x, y: cmp(x[2],y[2]))
 >>> temp
[(14, 22, 2), (3, 98, 7), (15, 67, 15), (57, 80, 33), (60, 78, 35), (32, 
21, 39), (70, 95, 39), (21, 92, 69), (16, 70, 87), (40, 18, 90)]

or, without lambdas:

 >>> def sort(x,y):
    return cmp(x[0],y[0])

 >>> def sort1(x,y):
    return cmp(x[1],y[1])

 >>> def sort2(x,y):
    return cmp(x[2],y[2])

 >>> temp.sort(cmp=sort)
 >>> temp
[(3, 98, 7), (14, 22, 2), (15, 67, 15), (16, 70, 87), (21, 92, 69), (32, 
21, 39), (40, 18, 90), (57, 80, 33), (60, 78, 35), (70, 95, 39)]
 >>> temp.sort(cmp=sort1)
 >>> temp
[(40, 18, 90), (32, 21, 39), (14, 22, 2), (15, 67, 15), (16, 70, 87), 
(60, 78, 35), (57, 80, 33), (21, 92, 69), (70, 95, 39), (3, 98, 7)]
 >>> temp.sort(cmp=sort2)
 >>> temp
[(14, 22, 2), (3, 98, 7), (15, 67, 15), (57, 80, 33), (60, 78, 35), (32, 
21, 39), (70, 95, 39), (21, 92, 69), (16, 70, 87), (40, 18, 90)]

Rinzwind wrote:

> Thank you!
> *opens manual again*
>
> Wim
>
> On 1/26/06, *Orri Ganel* <singingxduck at gmail.com 
> <mailto:singingxduck at gmail.com>> wrote:
>
>     Well, the cmp() function does this if you compare the number to 0:
>
>     >>> cmp(-34,0)
>     -1
>     >>> cmp(0,0)
>     0
>     >>> cmp(23,0)
>     1
>
>     Of course, that's not all cmp() is good for, but it would work in
>     this case.
>
>     HTH,
>     Orri
>
>-- 
>Email: singingxduck AT gmail DOT com
>AIM: singingxduck
>Programming Python for the fun of it.
>
>
>------------------------------------------------------------------------
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>  
>


-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060126/271269ce/attachment-0001.html 


More information about the Tutor mailing list