12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

11.1. Dictionary as asetof counters 1051. Youcouldcreate26variables,oneforeachletterofthealphabet. Thenyoucouldtraversethestringand,foreachcharacter,incrementthecorresponding counter,probablyusingachainedconditional.2. You could create a list with 26 elements. Then you could convert each character to a number(using the built-in function ord), use the number as an index into the list, and increment theappropriate counter.3. Youcouldcreateadictionarywithcharactersaskeysandcountersasthecorrespondingvalues.The first time you see a character, you would add an item to the dictionary. After that youwould increment thevalue of an existingitem.Eachoftheseoptionsperformsthesamecomputation,buteachofthemimplementsthatcomputationinadifferent way.An implementation is a way of performing a computation; some implementations are better thanothers. For example, an advantage of the dictionary implementation is that we don’t have to knowahead of time which letters appear in the string and we only have to make room for the letters thatdo appear.Here iswhat the code might look like:def histogram(s):d = dict()for c in s:if c not in d:d[c] = 1else:d[c] += 1return dThe name of the function is histogram, which is a statistical term for a set of counters (or frequencies).The first line of the function creates an empty dictionary. The for loop traverses the string. Eachtimethroughtheloop,ifthecharactercisnotinthedictionary,wecreateanewitemwithkeycandtheinitialvalue1(sincewehaveseenthisletteronce). Ifcisalreadyinthedictionaryweincrementd[c].Here’s how itworks:>>> h = histogram('brontosaurus')>>> print h{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}The histogram indicates that theletters’a’and'b'appear once;'o'appears twice, and soon.Exercise11.2 Dictionarieshaveamethodcalledgetthattakesakeyandadefaultvalue. Ifthekeyappearsinthedictionary,getreturnsthecorrespondingvalue;otherwiseitreturnsthedefaultvalue.For example:>>> h = histogram('a')>>> print h{'a': 1}

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

Saved successfully!

Ooh no, something went wrong!