I have an issue with sorting a simple string by frequency (I get a string as an input, and I need to give a sorted string back as an output in descending order). Let me give you an example (the original word contains 4 e's, 2 s's, 1 t, 1 r and 1 d; so these get sorted):
In [1]: frequency_sort("treeseeds")
Out [1]: "eeeesstrd"
Most solutions on Stack Overflow state that I should use the sorted()
function to get my results, however, it only seems to work with certain cases.
I made two functions that supposed to work, but none of them seems to do the trick with my specific inputs (see below).
First function:
def frequency_sort(s):
s_sorted = sorted(s, key=s.count, reverse=True)
s_sorted = ''.join(c for c in s_sorted)
return s_sorted
Second function:
import collections
def frequency_sort_with_counter(s):
counter = collections.Counter(s)
s_sorted = sorted(s, key=counter.get, reverse=True)
s_sorted = ''.join(c for c in s_sorted)
return s_sorted
With both functions my outputs look like this:
The first output is okay:
In [1]: frequency_sort("loveleee")
Out [1]: "eeeellov"
The second output is not so much
In [2]: frequency_sort("loveleel")
Out [2]: "leleelov"
The third output is totally messy:
In [3]: frequency_sort("oloveleelo")
Out [3]: "oloeleelov"
What could have gone wrong? Is it connected to the 'o' and 'l' characters somehow? Or am I just missing something?