DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Day 33: Python Sort by Vowels, Custom Sorting Fruits by Vowel Count with Keys

Welcome to Day 33 of the #80DaysOfChallenges journey! Today's beginner challenge is on sorting a list of words by the number of vowels they contain, using a helper function as the key for sorted() to count a's, e's, i's, o's, u's case-insensitively. This sharpens custom sort logic, string iteration, and lambda alternatives, handy for text sorting or analysis tasks. If you're getting into keys for sorting or counting in strings, this "Python sort by vowels" tutorial highlights a function pair that's clean and extends to other criteria like consonants or length.


💡 Key Takeaways from Day 33: Vowel Sort Functions

This task features a counter function feeding into sorted() for vowel-based order, with fewer vowels first. It's a prime example of modular sorting: define metric, apply key, get results. We'll cover the core: vowel count with sum generator, sorted with custom key, and example with fruit list.

1. Vowel Counter: Case-Insensitive Sum

The count_vowels function scans a word and tallies vowels. Its signature is typed:

def count_vowels(word: str) -> int:
    """
    Return the number of vowels in the given word (case-insensitive).
    """
Enter fullscreen mode Exit fullscreen mode

The logic:

vowels = "aeiou"
return sum(1 for char in word.lower() if char in vowels)
Enter fullscreen mode Exit fullscreen mode

.lower() ensures case doesn't matter, and the generator with in counts efficiently. It's pure, no side effects, perfect as a key since it returns ints for comparison. This pattern works for any char set, like counting specific letters or digits.

2. Sort Function: Use Counter as Key

The sort_by_vowel_count wraps sorted():

def sort_by_vowel_count(words: list[str]) -> list[str]:
    """
    Return a new list of words sorted by number of vowels.
    """
    return sorted(words, key=count_vowels)
Enter fullscreen mode Exit fullscreen mode

key=count_vowels applies the counter to each word, sorting ascending by default. It creates a new list, preserving the original, and handles ties by stable order. Easy to flip with reverse=True or combine keys for multi-criteria.

3. Example Usage: Fruits Sorted

Run it under main:

if __name__ == "__main__":
    fruits = ["Apple", "Banana", "Watermelon", "Cherry", "Melon", "Strawberry", "Orange", "Kiwi", "Mango"]
    sorted_fruits = sort_by_vowel_count(fruits)
    print(f"\n🔤 Sorted by vowel count: {sorted_fruits}\n")
Enter fullscreen mode Exit fullscreen mode

For this list, it might output something like ['Kiwi', 'Mango', 'Apple', 'Melon', 'Cherry', 'Orange', 'Banana', 'Strawberry', 'Watermelon'] based on counts (e.g., Kiwi:2, Watermelon:4). The print gives quick feedback, and you could add counts in output for clarity.


🎯 Summary and Reflections

This vowel sorter illustrates custom keys turning basic sorted() into targeted tools for data. It stuck with me:

  • Generator efficiency: Sum with if in is concise for counts.
  • Key modularity: Separate function makes testing and reuse simple.
  • String handling: lower() and in for easy analysis.

The insight? How this applies to NLP basics, like sorting by frequency. For extras, handle y as vowel or sort descending.

Advanced Alternatives: Inline lambda: sorted(words, key=lambda w: sum(1 for c in w.lower() if c in 'aeiou')), or Counter for vowels per word. How do you customize sorts? Comment your fav!


🚀 Next Steps and Resources

Day 33 enhanced sorting with text metrics, gearing for more string challenges. In #80DaysOfChallenges? Counted differently? Share your code!

Top comments (0)