palindrome iteration

Richard Arts arts.richard at
Fri Aug 27 12:40:01 CEST 2010

> Now there is another solution. A palindrom is made of two symetric halves,
> with (odd len) or without (even len) a single char between the symetric
> halves, ie :
> * odd : ABCBA ('AB' + 'C' + 'BA')
> * even : ABCCBA ('ABC' + 'CBA')
> So you just have to extract the symetric halves, reverse one, and compare
> both (case insensitive compare while we're at it).

Yes, this is a correct observation, but it is not necessary to compare
the halves; Simply compare the complete string with its reverse. If
they match, it is a palindrome.

> Here's a possible (and a
> bit tricky) Python 2.x implementation:
> def is_palindrom(s):
>    s = s.lower()
>    slen = len(s)
>    until = slen / 2 # Python 2x integer division
>    offset = int(not(slen % 2))
>    runtil = until - offset
>    return s[0:until] == s[-1:runtil:-1]

At first glance this seems to be correct, but it is tricky indeed.
Particularly the assignment of the offset variable, casting a bool to
an integer of a negated expression. Given that Baba notes that this is
a beginners level query, it wouldn't have hurt to be a little bit more
verbose there.


More information about the Python-list mailing list