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.

10.15. Exercises 101Exercise 10.6 Write a function called remove_duplicates that takes a list and returns a new listwithonly theunique elements from theoriginal. Hint: they don’t have tobe inthe sameorder.Exercise10.7 Writeafunctionthatreadsthefilewords.txtandbuildsalistwithoneelementperword. Write two versions of this function, one using the append method and the other using theidiomt = t + [x]. Which one takes longer torun? Why?You can see mysolutionatthinkpython.com/code/wordlist.py.Exercise 10.8 To check whether a word is in the word list, you could use the in operator, but itwould be slow because itsearches through thewords inorder.Because the words are in alphabetical order, we can speed things up with a bisection search (alsoknownasbinarysearch),whichissimilartowhatyoudowhenyoulookawordupinthedictionary.You start in the middle and check to see whether the word you are looking for comes before thewordinthemiddleofthelist. Ifso,thenyousearchthefirsthalfofthelistthesameway. Otherwiseyou search thesecond half.Either way, you cut the remaining search space in half. If the word list has 113,809 words, it willtake about 17 steps tofind theword orconclude that it’snot there.Writeafunctioncalledbisectthattakesasortedlistandatargetvalueandreturnstheindexofthevalue inthelist,ifit’sthere, orNoneifit’snot.Or you could read thedocumentation of thebisectmodule and usethat!Exercise 10.9 Two words are a “reverse pair” if each is the reverse of the other. Write a programthat finds all thereverse pairs intheword list.Exercise 10.10 Two words “interlock” if taking alternating letters from each forms a new word 1 .For example, “shoe” and “cold” interlock toform“schooled.”1. Writeaprogram that finds all pairsof words that interlock. Hint: don’t enumerate all pairs!2. Canyoufindanywordsthatarethree-wayinterlocked;thatis,everythirdletterformsaword,startingfrom thefirst,second orthird?1 This exercise is inspired byanexampleatpuzzlers.org.

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

Saved successfully!

Ooh no, something went wrong!