Codative 🔭
1.18K subscribers
535 photos
34 videos
26 files
272 links
Programmer | Orthodox Christian | Reader

Resources: @codative_resources
Download Telegram
Have You Ever Got Stuck Comparing Values in Python Sorting? Meet cmp_to_key!

If you've been solving problems on LeetCode or coding challenges in general, you’ve probably faced a situation where you need custom sorting logic—like sorting based on multiple conditions. This is where Python's cmp_to_key comes in, and it can save the day!What is cmp_to_key?Imagine you have a comparison function that says,
If this value is smaller than that, return -1; if they're equal, return 0; if it's bigger, return 1.


This is called a comparison function (cmp). But modern Python sorting methods like sorted() or .sort() use a key function instead.So how do you use your custom cmp function with sorted()? Simple—convert it using cmp_to_key!

Example:

Sorting Strings by Length, Then AlphabeticallyLet’s say you need to sort a list of words. First, by length. If two words have the same length, you sort them alphabetically.

from functools import cmp_to_key

def compare(a, b):
if len(a) == len(b):
return -1 if a < b else 1 # Compare alphabetically if lengths are equal
return len(a) - len(b) # Compare by length

words = ["apple", "bat", "banana", "pie", "cat"]
sorted_words = sorted(words, key=cmp_to_key(compare))

print(sorted_words) # Output: ['bat', 'cat', 'pie', 'apple', 'banana']


Without cmp_to_key, writing such sorting logic can get messy. But here, you just write your comparison function, and cmp_to_key handles the rest.Example: Custom Sorting NumbersLet’s sort a list of numbers where we want even numbers first, sorted in descending order, and odd numbers second, sorted in ascending order.

def custom_compare(a, b):
if a % 2 == b % 2: # Both even or both odd
return b - a if a % 2 == 0 else a - b # Descending for evens, ascending for odds
return -1 if a % 2 == 0 else 1 # Even before odd

numbers = [3, 1, 4, 10, 5, 6, 7]
sorted_numbers = sorted(numbers, key=cmp_to_key(custom_compare))

print(sorted_numbers) # Output: [10, 6, 4, 1, 3, 5, 7]

How Does It Work?

If a should come before b, return -1.If a and b are equal, return 0.If a should come after b, return 1.

#tips #leetcode #python
@codative
👍1