Write a Python function called hist() which takes a string as an argument, and creates a visual representation of the frequency of its alphabetic letters by printing each letter in uppercase the number of times it appears in the string, with each letter on a separate line, grouped from mo开发者_高级运维st to least.
A MUCH simpler approach is:
import string
def hist(s):
d = {}
for i in s.upper():
if i.isalpha():
d[i] = d[i] + 1 if i in d else 1
for k in sorted(d.keys()):
print k*d[k]
Your code is similar, you don't need to read the file.
def hist(inputstr):
lowlet = inputstr.upper()
alphas = 'abcdefghijklmnopqrstuvwxyz'.upper()
occurrences = dict( (letter, 0) for letter in alphas)
total = 0
for letter in lowlet:
if letter in occurrences:
total += 1
occurrences[letter] += 1
letcount = sorted(occurrences.iteritems(),key = lambda x:-x[1])
for letter, count in letcount:
if count>0:
print letter*count
精彩评论