-7

I tried to define a function to print the letters of a word in decreasing order of their frequency, using dictionary and tuple. Two similar questions were Counting repeated characters in a string in Python and How to write a function that takes a string and prints the letters in decreasing order of frequency?, but the difference is the sorting (by frequency) part and the algorithm.

Here's what I wrote :-

def most_frequent(string):
    d = dict()        #Created a dictionary
    for c in string:
        d[c] = d.get(c,0)+1  #Employed the get method to get the value of the key c
    t = d.items()     #Created a list of tuples of key-value pairs
    for letter, frequency in t:
        letter, frequency = frequency, letter  #Swapped the elements of the tuples
    t.sort(reverse = True)     #Sorting in descending order
    for frequency, letter in t:
        print (frequency," ",letter)

The error message produced when I call the function with "bookshopkeeper" as the argument is :-

    Traceback (most recent call last):
      File "<pyshell#2>", line 1, in <module>
        most_frequent("bookshopkeeper")
      File "<pyshell#1>", line 8, in most_frequent
        t.sort(reverse = True)
    AttributeError: 'dict_items' object has no attribute 'sort'

I used the get method to eliminate use of if conditionals. I am using python 3.3. Please fix the code. Thanks a lot.

Community
  • 1
  • 1
  • 3
    Please fix the code identation. – ρss May 08 '14 at 18:56
  • 1
    Please do fix your indentation, your code is hard to comprehend in terms of logic. Also, what exactly isn't working about it? – anon582847382 May 08 '14 at 18:56
  • 1
    Isn't working means what? Crashes with error? Incorrect output? Nasal demon infestation? – Daenyth May 08 '14 at 18:58
  • possible duplicate of [Counting repeated characters in a string in Python](http://stackoverflow.com/questions/991350/counting-repeated-characters-in-a-string-in-python) – wflynny May 08 '14 at 18:59
  • [Please read this](http://meta.stackoverflow.com/questions/253787/are-there-legitimate-fix-my-code-questions) for what constitutes an on-topic "fix my code" question. As posted, this is clearly off topic and I have voted to close it. – roippi May 08 '14 at 18:59
  • To fix indentation: copy your code (with correct indentation) into the question box. Select all of the code, and hit `Ctrl-K` (`Cmd-K` on OS X). – MattDMo May 08 '14 at 19:00

1 Answers1

3

You're better off using a collections.Counter.

dct = collections.Counter(string)
print(dct.most_common())
print(list(reversed(dct.most_common())))  # least common :-)
mgilson
  • 300,191
  • 65
  • 633
  • 696