I have a problem with sorting a simple string by frequency (I get the string as input, and I need to pass the sorted string as output in descending order). Let me give you an example (the original word contains 4 e, 2 s, 1 t, 1 r and 1 d, so they are sorted):
In [1]: frequency_sort("treeseeds")
Out [1]: "eeeesstrd"
In most decisions in mode, I have to use the function sorted()to get my results, however it only works with some cases.
I made two functions that should have worked, but none of them seem 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
In both functions, my outputs look like this:
The first output is fine:
In [1]: frequency_sort("loveleee")
Out [1]: "eeeellov"
Second conclusion is not much
In [2]: frequency_sort("loveleel")
Out [2]: "leleelov"
The third conclusion is completely messy:
In [3]: frequency_sort("oloveleelo")
Out [3]: "oloeleelov"
? "o" "l"? - ?