def compare(a, b):
"""
Return 1 if a > b, 0 if a equals b, and -1 if a < b
>>> compare (5, 7)
1
>>> compare (7, 7)
0
>>> compare (2, 3)
-1
"""
Asked
Active
Viewed 2.1k times
2

jamylak
- 128,818
- 30
- 231
- 230

Jordan Ruatoe
- 21
- 1
- 1
- 2
-
3your examples are wrong – jamylak May 16 '13 at 06:02
-
3If you are writing a compare function in order to pass it to `sort`, this practice is deprecated - write a `key` function instead, it is both *not* deprecated *and* faster. – PaulMcG May 16 '13 at 06:50
-
Also note that this function already exists as the builtin `cmp` – Eric May 16 '13 at 07:08
1 Answers
12
>>> def compare(a, b):
return (a > b) - (a < b)
>>> compare(5, 7)
-1
>>> compare(7, 7)
0
>>> compare(3, 2)
1
A longer, more verbose way would be:
def compare(a, b):
return 1 if a > b else 0 if a == b else -1
Which, when flattened out looks like:
def compare(a, b):
if a > b:
return 1
elif a == b:
return 0
else:
return -1
The first solution is the way to go, remember it is pythonic to treat bool
s like int
s
Also note that that Python 2 has a cmp
function which does this:
>>> cmp(5, 7)
-1
however in Python 3 cmp
is gone, since the comparisons it is usually used for eg. list.sort
are now down using a key
function instead of cmp
.