Palindrome

Andrew Dalke adalke at mindspring.com
Thu Nov 13 04:25:27 EST 2003


Ulrich Schramme:
> I´m not very experienced with Python but I think you could do it in a
> more simple way.

Looks good to me.  And it shows that I'm no longer able to help out
beginning programmers since my solution is along the lines of

inp = raw_input('Enter a string: ')

punctuation = '%$!*.,-:? ;()\'\"\\'
foldcase = [chr(i) for i in range(256)]
for upper, lower in zip(string.ascii_uppercase, string.ascii_lowercase):
                  foldcase[ord(upper)] = lower
foldcase = "".join(foldcase)

t = inp.translate(foldcase, punctuation)
if t != t[::-1]:
      print '"' + inp + '" ' + 'is a palindrome.'
else:
     print '"' + inp + '" ' + 'is not a palindrome.'

Faster, but with a startup cost and a high learning curve.
It's what I would use for my own code.

A slightly easier to understand and slower version is

inp = raw_input('Enter a string: ')
punctuation = '%$!*.,-:? ;()\'\"\\'
identity = "".join([chr(i) for i in range(256)])

t = inp.translate(identity, punctuation).lower()
if t != t[::-1]:
  ...

Yours is definitely easiest to understand so best for
the OP.

Cheers,
                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list