Character Frequency Sorting Function

  • Share this:

Code introduction


This function takes an input string and uses collections.Counter to count the frequency of each character. It then sorts the characters by frequency in descending order and alphabetically in case of a tie, and finally returns a new string composed of the sorted characters.


Technology Stack : collections, string

Code Type : String processing

Code Difficulty : Intermediate


                
                    
def sorted_string(input_str):
    from collections import Counter
    from string import ascii_lowercase

    # Count the occurrences of each character in the input string
    counter = Counter(input_str)
    # Sort the characters by their occurrences and then alphabetically
    sorted_chars = sorted(counter.items(), key=lambda x: (-x[1], x[0]))
    # Create a string from the sorted characters
    sorted_str = ''.join([char * count for char, count in sorted_chars])
    return sorted_str