Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.x return values for cmp

Quoted from the docs:

cmp(x, y)

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

I was under the assumption that the return values are always -1, 0, and 1 but the docs don't explicitly say that, only mentioning zero and positive/negative return value.

Are there any situations when the return value of cmp(x,y) is not -1, 0, or 1?

like image 874
jamylak Avatar asked May 17 '12 11:05

jamylak


People also ask

What does CMP return in Python?

The cmp() is part of the python standard library which compares two integers. The result of comparison is -1 if the first integer is smaller than second and 1 if the first integer is greater than the second. If both are equal the result of cmp() is zero.

Why was CMP removed from Python 3?

from python wiki: In Py3. 0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__ methods). The latter is very verbose and the same purpose is achieved in the former with just one line.

Does CMP work in Python 3?

cmp() does not work in python 3.

Why we use CMP list list2 in Python?

cmp(list) is a method specified in Number in Python 2. The comparison of integral numbers have been discussed using cmp(). But many a times, there is a need to compare the entire list that can be composed of similar or different data types.


2 Answers

No, the docs explicitly say that yalues can be anything. The only value that is specified is 0 if the compared objects are equal. Don't trust the fact that you only see the values -1, 0 and 1, that's an implementation detail and could change*, so always check for < and > 0.

*: note - actually, it won't really have a chance to change, since cmp has gone away in pyhton3. use rich comparison instead.

like image 173
mata Avatar answered Oct 26 '22 13:10

mata


Only 0 can be relied on, although the docstring for list.sort is interesting:

print list.sort.__doc__
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1

But in fact, sort doesn't actually impose this on it's comparison function as can be seen here:

def mycmp(a, b):
    print "mycmp(): a - b = ", a - b
    return a - b

L = [50, 30, 20, 40, 70, 50]

>>> L.sort(cmp=mycmp)
mycmp(): a - b =  -20
mycmp(): a - b =  -10
mycmp(): a - b =  20
mycmp(): a - b =  10
mycmp(): a - b =  -10
mycmp(): a - b =  30
mycmp(): a - b =  20
mycmp(): a - b =  10
mycmp(): a - b =  -20
mycmp(): a - b =  0

>>> print L
[20, 30, 40, 50, 50, 70]

Just for interest, but clearly sort is working happily with values other than -1, 0, or +1, so you should be too!

like image 27
mhawke Avatar answered Oct 26 '22 11:10

mhawke