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.

78 Chapter 8. StringsIf we test this function with the words “pots” and “stop”, we expect the return value True, but weget an IndexError:>>> is_reverse('pots', 'stop')...File "reverse.py", line 15, in is_reverseif word1[i] != word2[j]:IndexError: string index out of rangeFor debugging this kind of error, my first move is to print the values of the indices immediatelybefore thelinewhere the errorappears.while j > 0:print i, j# print hereif word1[i] != word2[j]:return Falsei = i+1j = j-1Now when I runtheprogram again, I get moreinformation:>>> is_reverse('pots', 'stop')0 4...IndexError: string index out of rangeThefirsttimethroughtheloop,thevalueofjis4,whichisoutofrangeforthestring'pots'. Theindex of thelastcharacter is3, sotheinitialvalue forjshould belen(word2)-1.IfIfix that error and runthe program again, I get:>>> is_reverse('pots', 'stop')0 31 22 1TrueThistimewegettherightanswer,butitlookslikethelooponlyranthreetimes,whichissuspicious.To get a better idea of what is happening, it is useful to draw a state diagram. During the firstiteration, theframeforis_reverselooks likethis:word1 ’pots’ word2 ’stop’i 0 j 3Itookalittlelicensebyarrangingthevariablesintheframeandaddingdottedlinestoshowthatthevalues ofiandjindicate characters inword1andword2.Exercise 8.8 Starting with this diagram, execute the program on paper, changing the values of iandjduring each iteration. Find and fixthe second error inthisfunction.

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

Saved successfully!

Ooh no, something went wrong!