[Tutor] How to find reverse pair words in a list of Words that has to be accessed through a URL

Steven D'Aprano steve at pearwood.info
Sat Apr 20 02:48:31 CEST 2013


On 20/04/13 09:57, Alan Gauld wrote:
> On 19/04/13 23:16, emile wrote:
>
>> The gotcha with this approach is the border case of self paired words
>> that aren't pairs.  (pop,wow,mom,etc)
>
> yeah, but those exceptions are easy to catch as you generate the reversed list:
>
> if reversed(word) == word


An easy mistake to make, but reversed() returns an iterator which will only
compare equal to itself:

py> reversed("abc")
<reversed object at 0xb7ea256c>


You need to convert the reversed object back into a string:

py> "".join(reversed("abc"))
'cba'


But the best way to reverse a string is with a slice:

py> 'abc'[::-1]
'cba'


The syntax is a little obscure, but "slicing" takes between 0 and 3 arguments,
written inside square brackets [ ] and separated by colons. The full form of a
slice is:

string[start:end:step]

where start defaults to the beginning of the string, end defaults to the end of
the string, and step defaults to 1. If step is 1, you can leave it out:

string[start:end]

otherwise you need to include colons to mark the missing values:

string[2::3]

says to return a slice of the string, starting at character 2, going to the end,
and taking every third character. (Remember that counting starts at 0 in Python,
not 1, so character 2 is the *third* character.)

py> "python is cool"[2::3]
'tnso'


A negative step goes backwards, so a fast and efficient way to reverse a string
or other sequence is to use slice it using [::-1].



> And its a bit of a moot point whether you should
> perhaps count a palindromic word as a pair of itself...

That word you use, I do not think it means what you think it means, to quote
the Spaniard.

A moot point is a point which is not relevant. If your house has just been
flattened by a hurricane, it is a moot point whether or not you left the front
door unlocked. I think it is quite relevant whether or not palindromes should
count or not.



-- 
Steven


More information about the Tutor mailing list