If you are familiar with some builtin high-order functions and methods such as sorted()
, filter
, min()
, max()
, reduce()
, etc, you might already be familiar with how key function works.
A key function allows you to define a specific criteria to be used for establishing order in a collection of items. Typically, key functions takes a single argument and returns a value that the sorting or ordering algorithm will use to compare elements in the collection.
compare elements by their absolute values
def absolute(x):
return x if x > 0 else -x
L = [0, -2, 5, 1, -4, 3]
#get the smallest item by absolute value
print(min(L, key = absolute))
#get the largest item by absolute value
print(max(L, key = absolute))
#sort the elements based on their absolute values
print(sorted(L, key = absolute))
How cmp_to_key() function works
The cmp_to_key()
function converts a comparison function to a key function which can be used as an ordering criteria. Typically, a comparison function takes two arguments and returns a negative( usually -1), zero, or positive( usually 1) number depending on whether the comparison operation evaluates to False, equal, or True, respectively.
@cmp_to_key
def cmp_func(x, y):
#statements
or
def cmp_func(x, y):
#statements
key_func = cmp_to_key(func)
from functools import cmp_to_key
#function to get the larger item by absolute value
@cmp_to_key
def absolute_larger(x, y):
if abs(x) > abs(y):
return 1
elif abs(x) < abs(y):
return -1
return 0
L = [-1, 5, -2, 3, -8, 0, 7]
print(min(L, key= absolute_larger ))
print(max(L, key= absolute_larger ))
print(sorted(L, key= absolute_larger ))
If the comparison function has already been defined or for some reason you do not want to use the @ decorator syntax, you can achive the same as shown below.
from functools import cmp_to_key
#function to get the larger item by absolute value
def absolute_larger(x, y):
if abs(x) > abs(y):
return 1
elif abs(x) < abs(y):
return -1
return 0
L = [-1, 5, -2, 3, -8, 0, 7]
print(min(L, key= cmp_to_key(absolute_larger) ))
print(max(L, key= cmp_to_key(absolute_larger) ))
print(sorted(L, key= cmp_to_key(absolute_larger) ))