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,
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.
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.
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
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
functools is crazy surprising me again with
accumulate a function for calculating the prefix sum of an array💯1
Forwarded from Henok | Neural Nets
48th ICPC World Finals was completed yesterday and Peking University got the first place.
Here are the problems for this year. I went over them and there is like 1 question I've tried and barely solved, they are hard😰
https://scoreboard.icpc.global/2024/problemset.pdf
Here are the problems for this year. I went over them and there is like 1 question I've tried and barely solved, they are hard😰
https://scoreboard.icpc.global/2024/problemset.pdf
Preparing for interviews and looking for resources I got you covered check this a collection of interview resources.
#resources #interview
@codative
#resources #interview
@codative
Medium
6 Best Resources for Tech Interview Preparation in 2024
My favorite resources to prepare for tech interviews
👍2
🚨 Live Stream Announcement! 🚨
Join me for an exciting live stream with Kibrnew Gedamu, a Codeforces expert, where we'll dive deep into the world of competitive programming and discuss programming in general! Whether you're just starting or looking to sharpen your skills, this stream is for you.
🗓 Date: Saturday, Sep 28
⏰ Time: 03:00PM LT
We'll cover tips, problem-solving strategies, and insights from Kibrnew's journey. Don't miss this chance to learn from one of the best!See you there! 👨💻
@codative
#CompetitiveProgramming #Codeforces #Programming #LiveStream #Codative
Join me for an exciting live stream with Kibrnew Gedamu, a Codeforces expert, where we'll dive deep into the world of competitive programming and discuss programming in general! Whether you're just starting or looking to sharpen your skills, this stream is for you.
🗓 Date: Saturday, Sep 28
⏰ Time: 03:00PM LT
We'll cover tips, problem-solving strategies, and insights from Kibrnew's journey. Don't miss this chance to learn from one of the best!See you there! 👨💻
@codative
#CompetitiveProgramming #Codeforces #Programming #LiveStream #Codative
⚡6👍1
Exciting news!
Tomorrow marks a new chapter for our channel as we launch the very first episode of the Codative podcast! 🎙 Join us for insightful discussions and an awesome time together. Don't miss it!
@codative
#podcast #CompetitiveProgramming
Tomorrow marks a new chapter for our channel as we launch the very first episode of the Codative podcast! 🎙 Join us for insightful discussions and an awesome time together. Don't miss it!
@codative
#podcast #CompetitiveProgramming
❤🔥10
🎉 Thank You for 400 Subscribers! 🎉
I’m incredibly grateful to each and every one of you for joining me on this amazing journey. Reaching 400 subscribers is a big milestone, and it wouldn't have been possible without your support! 🙌
Whether you've been here since the beginning or just joined, I appreciate your engagement, feedback, and motivation. Here's to continuing this journey together, learning, growing, and building even more amazing things!
Let’s keep pushing forward! 🚀
Thank you again for being a part of this! 🙏
@codative
#milestone #gratitude #400subscribers #community
I’m incredibly grateful to each and every one of you for joining me on this amazing journey. Reaching 400 subscribers is a big milestone, and it wouldn't have been possible without your support! 🙌
Whether you've been here since the beginning or just joined, I appreciate your engagement, feedback, and motivation. Here's to continuing this journey together, learning, growing, and building even more amazing things!
Let’s keep pushing forward! 🚀
Thank you again for being a part of this! 🙏
@codative
#milestone #gratitude #400subscribers #community
🔥6
Forwarded from Solomon
For ETCPC participants!
🚀 Don’t miss out on this awesome Codeforces group (https://codeforces.com/group/Rilx5irOux)! It’s packed with official ECPC (Egypt) and ACPC (Africa & Arab) contests — a goldmine of practice to sharpen your skills before the big day! 🌍💻 Ready to take your competitive programming to the next level? Check it out now! 🔥
🚀 Don’t miss out on this awesome Codeforces group (https://codeforces.com/group/Rilx5irOux)! It’s packed with official ECPC (Egypt) and ACPC (Africa & Arab) contests — a goldmine of practice to sharpen your skills before the big day! 🌍💻 Ready to take your competitive programming to the next level? Check it out now! 🔥
Join this for finding contests and having discussion on codeforces there are a lot of things there
Telegram
Contest Discussion
Hey CP Community, welcome to our Contest Discussion group! This is a space where we can discuss contests, share tips, and help each other out.