Python Sort by frequency - do not sort using the sorted () function

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"? - ?

+4
3

, , , , , . ; .

In [7]: def frequency_sort(s):
        s_sorted = sorted(s, key=lambda c: (s.count(c), c), reverse=True)
        s_sorted = ''.join(c for c in s_sorted)
        return s_sorted
   ...: 

In [8]: frequency_sort("loveleel")
Out[8]: 'llleeevo'
+4

, , ( ), , :

s_sorted = ''.join(sorted(sorted(s), key=lambda x: s.count(x), reverse=True))

:

eeellloooav

:

s_sorted = ''.join(sorted(sorted(s, reverse=True), key=lambda x: s.count(x), reverse=True))

:

ooollleeeva
0

, sort sorted . , "" ( key(item1) == key(item2)), , sort.

, :

>>> from collections import Counter

>>> Counter("oloveleelo")
Counter({'e': 3, 'l': 3, 'o': 3, 'v': 1})

, 'e', 'l' 'o' key, , : "oloeleelo", , : 'v'.

( ), sorted, Counter.most_common:

>>> ''.join([item for item, cnt in Counter("oloveleelo").most_common() for _ in range(cnt)])
'llleeeooov'
>>> ''.join([item for item, cnt in Counter("loveleel").most_common() for _ in range(cnt)])
'eeelllov'
>>> ''.join([item for item, cnt in Counter("loveleee").most_common() for _ in range(cnt)])
'eeeellov'
0

Source: https://habr.com/ru/post/1678706/


All Articles