Reputation: 5
from collections import *
def compress(s):
res = Counter(s)
for key,value in res.items():
print(key, value)
compress("hhgoogle")
Output:
h 2
g 2
o 2
l 1
e 1
How to sort it in alphabetical order with respect to count, i.e.:
Required output:
g 2
h 2
o 2
e 1
l 1
Upvotes: 0
Views: 79
Reputation: 98921
You can use:
from collections import *
print(sorted(Counter('hhgoogle').items(), key=lambda x: (-x[1], x[0])))
# [('g', 2), ('h', 2), ('o', 2), ('e', 1), ('l', 1)]
Upvotes: 1
Reputation: 27557
Here is what you can do:
from collections import *
def compress(s):
res= Counter(s)
l1 = sorted(res.most_common(), key=lambda t: t[0])
l2 = sorted(l1, key=lambda t: t[1], reverse=True)
print('\n'.join([f"{t[0]} {t[1]}" for t in l2]))
compress("hhgoogle")
Output:
g 2
h 2
o 2
e 1
l 1
Upvotes: 0
Reputation: 1874
First sort it alphabetically, then sort the occurrences. The join is merely to output it in the format you have described.
from collections import *
def compress(s):
res= Counter(s)
alphabetic_res = sorted(res.most_common(), key=lambda tup: tup[0])
final_res = sorted(alphabetic_res, key=lambda tup: tup[1], reverse=True)
print("\n".join("%s,%s" % tup for tup in final_res))
compress("hhgoogle")
OUT: g,2
h,2
o,2
e,1
l,1
Upvotes: 0