palindrome iteration

Matteo Landi landimatte at gmail.com
Fri Aug 27 13:43:16 CEST 2010


> 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.

I've always used to implement the is_palindrome function as you
suggest, i.e. comparing the original string with the reverse one, but
while reading, I tought about a imho nicer version which prevent from
creating another string.

Here are both the recursive/iterative versions of the function:

def palindrome(str, i=0, j=-1):
	try:
	    if str[i] == str[j]:
	        return palindrome(str, i + 1, j - 1)
	    return False
	except IndexError:
	    return True

def palindrome(str, i=0, j=-1):
	try:
	    while True:
                if str[i] != str[j]:
		    return False
		i, j = i + 1, j - 1
	    return True
	except IndexError:
	    return True

Regards,
Matteo

>
>> 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.
>
> Richard
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/



More information about the Python-list mailing list