I have this string: s = "china construction bank"
. I want to create a function that returns the 3 most frequent characters and order them by their frequency of appearance and the number of times they appear, but if 2 characters appears the same number of times, they should be ordered based on their alphabetical order. I also want to print each character in a separate line.
I have built this code by now:
from collections import Counter
def ordered_letters(s, n=3):
ctr = Counter(c for c in s if c.isalpha())
print ''.join(sorted(x[0] for x in ctr.most_common(n)))[0], '\n', ''.join(sorted(x[0] for x in ctr.most_common(n)))[1], '\n', ''.join(sorted(x[0] for x in ctr.most_common(n)))[2]`
This code applied to the above string will yield:
a
c
n
But this is not what i really want, what i would like as output is:
1st most frequent: 'n'. Appearances: 4
2nd most frequent: 'c'. Appearances: 3
3rd most frequent: 'a'. Appearances: 2
I'm stuck in the part where i have to print in alphabetical order the characters which have the same frequencies. How could i do this?
Thank you very much in advance