definition
- cmp_to_key() uses key to compare elements
- It's built into the functools module, so functools must be imported to use the function
- Use with tools that accept key functions like min(), max(), sorted(), etc.
- Only accepts one argument that should strictly speaking be a callable
- This function returns a special key that can be used to compare elements
- Used to compare two values and return 1, -1 or 0
Example 1: A program that sorts a list using a key provided by the cmp_to_key() function
import functools
def mycmp(a, b):
print("comparing ", a, " and ", b)
if a > b:
return 1
elif a < b:
return -1
else:
return 0
print(sorted([1, 2, 4, 2], key=functools.cmp_to_key(mycmp)))
output:
comparing 2 and 1
comparing 4 and 2
comparing 2 and 4
comparing 2 and 2
comparing 2 and 4
[1, 2, 2, 4]
Example 2: Program to print the largest and smallest number from a list using the key provided by the cmp_to_key() function
import functools
def mycmp(a, b):
print("comparing ", a, " and ", b)
if a > b:
return 1
elif a < b:
return -1
else:
return 0
print(min([45, 78, 813], key=functools.cmp_to_key(mycmp)))
print(max([45, 78, 813], key=functools.cmp_to_key(mycmp)))
output:
comparing 78 and 45
comparing 813 and 45
45
comparing 78 and 45
comparing 813 and 78
813
-------------------------------------------------- -----The following is the topic of leetcode -------------------------------------- ------
Solution:
class Solution:
def largestNumber(self, nums):
def cmp_func(x, y):
if x + y > y + x:
return 1
elif x == y:
return 0
else:
return -1
nums = [str(num) for num in nums]
nums.sort(key = cmp_to_key(cmp_func), reverse = True)
return ''.join(nums).lstrip('0') or '0'