Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a function that takes a string and prints the letters in decreasing order of frequency?

Tags:

python

I got this far:

def most_frequent(string):
    d = dict()
    for key in string:
        if key not in d:
            d[key] = 1
        else:
            d[key] += 1
    return d

print most_frequent('aabbbc')

Returning:

{'a': 2, 'c': 1, 'b': 3}

Now I need to:

  1. reverse the pair
  2. sort by number by decreasing order
  3. only print the letters out

Should I convert this dictionary to tuples or list?

like image 410
prodev42 Avatar asked Nov 28 '22 08:11

prodev42


1 Answers

Here's a one line answer

sortedLetters = sorted(d.iteritems(), key=lambda (k,v): (v,k))
like image 117
chills42 Avatar answered Dec 24 '22 03:12

chills42