Home > Software design >  Python sort() with lambda key - list of nums vs chars
Python sort() with lambda key - list of nums vs chars

Time:09-17

I am trying to apply the solution of sorting a list of numbers by frequency of each number, but to a list of chars.

My solution for sorting the numbers is:

def num_sort_by_freq(list_of_nums):

    num_count = {}

    for num in list_of_nums:
        if num not in num_count:
            num_count[num] = 1
        else:
            num_count[num]  = 1

    list_of_nums.sort(key = lambda x:num_count[x])

    return list_of_nums

print(num_sort_by_freq([1,1,1,2,2,2,2,3,3,3]))

Output: [1, 1, 1, 3, 3, 3, 2, 2, 2, 2]

Trying to sort the chars:

def char_sort_by_freq(string_to_be_list):

    list_of_chars = list(string_to_be_list)

    char_count = {}

    for char in list_of_chars:
        if char not in char_count:
            char_count[char] = 1
        else:
            char_count[char]  = 1

    list_of_chars.sort(key = lambda x:char_count[x])

    return "".join(list_of_chars)

print(char_sort_by_freq("asdfasdfasdddffffff"))

Output: asasasdddddffffffff

Expected output: aaasssdddddffffffff

I've gone through it too many times and cannot understand why the output's 'a's and 's's are jumbled together, rather than sequential.

Any help is appreciated.

edit: Thanks so much for the help! Lambda functions are new territory for me.

CodePudding user response:

You can change your key function to return tuple to handle ties:

def char_sort_by_freq(string_to_be_list):

    list_of_chars = list(string_to_be_list)

    char_count = {}

    for char in list_of_chars:
        if char not in char_count:
            char_count[char] = 1
        else:
            char_count[char]  = 1

    list_of_chars.sort(key = lambda x:(char_count[x], x))
    #                                  ^^^^^^^^^^^^^^^^^
    return "".join(list_of_chars)

print(char_sort_by_freq("asdfasdfasdddffffff"))

Output:

aaasssdddddffffffff
  • Related