Re: Palindrome
From: Ron Adam (radam2_at_tampabay.rr.com)
Date: 11/14/03
- Next message: Alex Martelli: "Re: python a bust?"
- Previous message: Anand Pillai: "Re: Books I'd like to see"
- In reply to: Alan Kennedy: "Re: Palindrome"
- Next in thread: Ron Adam: "Re: Palindrome"
- Reply: Ron Adam: "Re: Palindrome"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 14 Nov 2003 11:51:02 GMT
On Thu, 13 Nov 2003 17:32:06 +0000, Alan Kennedy <alanmk@hotmail.com>
wrote:
>
>I'm not too happy with it though. There must be some way to have a
>single fixed regular expression that can be used to test every
>palindrome.
>
>regards,
Thought I'd give it a try too. This is what I came up with. I used
the regular expression re.sub() function to remove the punctuation and
spaces.
The really hard part was trying to come up with a palindrome that has
the word python in it. :-)
_Ron Adam
"""
Test if a string is a palindrome.
"""
import re
def palindrome_test(p):
p = p.lower()
p = re.sub(r'\W','',p)
while p:
if p[:1] == p[-1:]:
p = p[1:-1]
else:
break
if (len(p) <= 1):
return True
else:
return False
palindrome_list = ["Bolton",
"No 'H' type, mate. No spot stops one tame
python!",
"A man, a plan, a cat, a ham, a yak, a yam, a hat,
a canal--Panama!",
"Was it a car or a cat I saw?",
"This is not a palindrome!"]
for p in palindrome_list:
print '"'+p+'"',
if palindrome_test(p):
print 'is a palindrome.'
else:
print 'is not a palindrome.'
- Next message: Alex Martelli: "Re: python a bust?"
- Previous message: Anand Pillai: "Re: Books I'd like to see"
- In reply to: Alan Kennedy: "Re: Palindrome"
- Next in thread: Ron Adam: "Re: Palindrome"
- Reply: Ron Adam: "Re: Palindrome"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]