Sort Characters by Frequency

Advanced

Sort Characters by Frequency

Hey there, young coders! Here's a fun Python challenge for you. Imagine you have a magical notebook, and whenever you write a word in it, it rearranges the letters based on how many times each letter appears!

Your task is to create a magical function sort_characters_by_frequency that takes a single word and returns a new word. This new word should have its letters sorted by how frequently each letter appears in the original word, from most frequent to least frequent.

If two characters appear the same number of times, they should be ordered lexicographically (alphabetically).

Example:

Let's say we call the function with the word "bubble":

sort_characters_by_frequency("bubble")

The word "bubble" has:

  • 'b' appearing 2 times
  • 'u' appearing 1 time
  • 'l' appearing 1 time
  • 'e' appearing 1 time

In this case, the sorted version would be "bbelu" because:

  • 'b' appears the most, so it comes first.
  • 'e', 'l', and 'u' all appear once, but they are sorted lexicographically, so 'e' comes first, followed by 'l', then 'u'.

Another Example:

sort_characters_by_frequency("character")

In this case, the sorted version would be "ccaarrhte". Both 'c' and 'a' appear twice, but they are ordered lexicographically.

Have fun creating your magical notebook function!

Function Signature:

def sort_characters_by_frequency(s: str) -> str:
Geek
Inputs

Arg 1:

"bubble"
Expected Output
"bbbelu"
Actual Output
Sort Characters by Frequency [advanced] | Coding for Kids