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.

82 Chapter 9. Casestudy: word playThe next word is “aah,” which is a perfectly legitimate word, so stop looking at me like that. Or, ifit’sthewhitespace that’sbothering you, wecan get ridofit withthe stringmethodstrip:>>> line = fin.readline()>>> word = line.strip()>>> print wordaahedYou can also use a file object as part of a for loop. This program reads words.txt and prints eachword, one per line:fin = open('words.txt')for line in fin:word = line.strip()print wordExercise 9.1 Write a program that reads words.txt and prints only the words with more than 20characters (not counting whitespace).9.2 ExercisesTherearesolutionstotheseexercisesinthenextsection. Youshouldatleastattempteachonebeforeyou read thesolutions.Exercise9.2 In1939ErnestVincentWrightpublisheda50,000wordnovelcalledGadsbythatdoesnot contain theletter “e.” Since “e” isthe most common letterinEnglish, that’s not easy todo.In fact, it is difficult to construct a solitary thought without using that most common symbol. It isslow going at first,but withcaution and hours oftraining you can gradually gain facility.Allright, I’llstopnow.Write a function called has_no_e that returns True if the given word doesn’t have the letter “e” init.Modifyyourprogramfromtheprevioussectiontoprintonlythewordsthathaveno“e”andcomputethepercentage of the words inthelisthave no “e.”Exercise9.3 Writeafunctionnamedavoidsthattakesawordandastringofforbiddenletters,andthat returnsTrueiftheword doesn’t use any of the forbidden letters.Modify your program to prompt the user to enter a string of forbidden letters and then print thenumber of words that don’t contain any of them. Can you find a combination of 5 forbidden lettersthat excludes thesmallestnumber of words?Exercise 9.4 Write a function named uses_only that takes a word and a string of letters, and thatreturns True if the word contains only letters in the list. Can you make a sentence using only thelettersacefhlo? Other than “Hoe alfalfa?”Exercise 9.5 Write a function named uses_all that takes a word and a string of required letters,and that returns True if the word uses all the required letters at least once. How many words arethere that useall thevowelsaeiou? How aboutaeiouy?

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

Saved successfully!

Ooh no, something went wrong!