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.

9.3. Search 83Exercise 9.6 Write a function called is_abecedarian that returns True if the letters in a wordappear inalphabetical order (double lettersareok). How many abecedarian words are there?9.3 SearchAll of the exercises in the previous section have something in common; they can be solved with thesearch pattern wesaw inSection 8.6. The simplestexample is:def has_no_e(word):for letter in word:if letter == 'e':return Falsereturn TrueThe for loop traverses the characters in word. If we find the letter “e”, we can immediately returnFalse;otherwisewehavetogotothenextletter. Ifweexittheloopnormally,thatmeanswedidn’tfind an “e”, sowereturnTrue.avoidsisamore general version ofhas_no_ebut ithas thesame structure:def avoids(word, forbidden):for letter in word:if letter in forbidden:return Falsereturn TrueWecanreturnFalseassoonaswefindaforbiddenletter;ifwegettotheendoftheloop,wereturnTrue.uses_onlyissimilarexcept that thesense of thecondition isreversed:def uses_only(word, available):for letter in word:if letter not in available:return Falsereturn TrueInsteadofalistofforbiddenletters,wehavealistofavailableletters. Ifwefindaletterinwordthatisnot inavailable,wecan returnFalse.uses_allissimilarexcept that we reverse the roleofthe wordand the stringof letters:def uses_all(word, required):for letter in required:if letter not in word:return Falsereturn TrueInsteadoftraversingthelettersinword,thelooptraversestherequiredletters. Ifanyoftherequiredlettersdo not appear intheword, wecan returnFalse.Ifyouwerereallythinkinglikeacomputerscientist,youwouldhaverecognizedthatuses_allwasan instance of apreviously-solved problem, and you would have written:

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

Saved successfully!

Ooh no, something went wrong!