12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

128 Chapter 13. Casestudy: datastructure selection13.4 MostcommonwordsTo find the most common words, we can apply the DSU pattern; most_common takes a histogramand returns alistofword-frequency tuples, sortedinreverse order by frequency:def most_common(h):t = []for key, value in h.items():t.append((value, key))t.sort(reverse=True)return tHere isaloop that printsthe tenmost common words:t = most_common(hist)print 'The most common words are:'for freq, word in t[0:10]:print word, '\t', freqAnd here aretheresultsfrom Emma:The most common words are:to 5242the 5204and 4897of 4293i 3191a 3130it 2529her 2483was 2400she 236413.5 Optional parametersWehaveseenbuilt-infunctionsandmethodsthattakeavariablenumberofarguments. Itispossibleto write user-defined functions with optional arguments, too. For example, here is a function thatprintsthe most common words inahistogramdef print_most_common(hist, num=10):t = most_common(hist)print 'The most common words are:'for freq, word in t[0:num]:print word, '\t', freqThe firstparameter is required; the second isoptional. The default value ofnumis10.Ifyou only provide one argument:print_most_common(hist)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!