'''
Created on Nov 15, 2011

@author: rodger
'''
lista = ["sloth", "aardvark", "pangolin", "pangolin", \
         "aardvark", "sloth", "sloth", "numbat", "anteater" ]

# problem D

# First create a map of words to the number of occurences
counts = {}            
for word in lista:
    if word  in counts:
        counts[word] += 1
    else: 
        counts[word] = 1
        
print "Dictionary of words to counts: ", counts
        
# create an inverse map of counts to words that occur that many times
revCounts = {}
for (key,value) in counts.iteritems():
    if value in revCounts:
        revCounts[value].append(key)
    else:
        revCounts[value] = [key]

print "Dictionary of counts to words: ", revCounts

finalAnswer = []
countsSorted = revCounts.keys()  # list of the counts

countsSorted.sort(reverse=True)  # list of counts in reverse order

print "Counts in reverse order: ", countsSorted
# create the answer, for each count get the list of words for
# that count, sort them, and then append them to the answer list
for cnt in countsSorted:
    words = revCounts[cnt]
    words.sort()
    for word in words:
        finalAnswer.append(word)  # appends list of words to the end
    
print "final answer is ", finalAnswer
        
