Is there a simple function available that compares numbers x and y and returns -1 when x is less than y, 1 when x is more than y and 0 when they're equal?
If not what is the shortest way to do so?
CodePudding user response:
There was a cmp()
method in Python2 that could do exactly what you require, however it was discontinued in Python 3. You can create this method likewise:
def compare(a, b):
return (a > b) - (a < b)
It has been mentioned in the documentation here.
The cmp() function should be treated as gone, and the cmp() special method is no longer supported. Use lt() for sorting, eq() with hash(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)