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.

84 Chapter 9. Casestudy: word playdef uses_all(word, required):return uses_only(required, word)This is an example of a program development method called problem recognition, which meansthat you recognize the problem you are working on as an instance of a previously-solved problem,and apply apreviously-developed solution.9.4 Looping with indicesI wrote the functions in the previous section withfor loops because I only needed the characters inthestrings;Ididn’t have todoanything withtheindices.Foris_abecedarianwe have tocompare adjacent letters,which isalittletrickywithaforloop:def is_abecedarian(word):previous = word[0]for c in word:if c < previous:return Falseprevious = creturn TrueAnalternative istouse recursion:def is_abecedarian(word):if len(word) word[1]:return Falsereturn is_abecedarian(word[1:])Another option istouse awhileloop:def is_abecedarian(word):i = 0while i < len(word)-1:if word[i+1] < word[i]:return Falsei = i+1return TrueTheloopstartsati=0andendswheni=len(word)-1. Eachtimethroughtheloop,itcomparestheith character (which you can think of as the current character) to the i+1th character (which youcan think of asthe next).If the next character is less than (alphabetically before) the current one, then we have discovered abreak inthe abecedarian trend, and wereturnFalse.If we get to the end of the loop without finding a fault, then the word passes the test. To convinceyourself that the loop ends correctly, consider an example like'flossy'. The length of the wordis 6, so the last time the loop runs is when i is 4, which is the index of the second-to-last character.Onthe lastiteration, itcompares thesecond-to-last character tothe last,which iswhat wewant.

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

Saved successfully!

Ooh no, something went wrong!