Chinaunix首页 | 论坛 | 博客
  • 博客访问: 204016
  • 博文数量: 23
  • 博客积分: 534
  • 博客等级: 下士
  • 技术积分: 245
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-20 16:27
文章分类

全部博文(23)

文章存档

2015年(1)

2012年(21)

2011年(1)

分类: Python/Ruby

2012-02-08 22:12:44

  1. # check if a phrase is a palindrome
  2. # tested with Python24 vegaseat 10sep2006

  3. def isPalindrome(phrase):
  4.     """
  5.     take a phrase and convert to all lowercase letters and
  6.     ignore punctuation marks and whitespaces,
  7.     if it matches the reverse spelling then it is a palindrome
  8.     """
  9.     phrase_letters = [c for c in phrase.lower() if c.isalpha()]
  10.     print phrase_letters # test
  11.     return (phrase_letters == phrase_letters[::-1])


  12. phrase1 = "A man, a plan, a canal, Panama!" # example with punctuation marks
  13. if isPalindrome(phrase1):
  14.     print '"%s" is a palindrome' % phrase1
  15. else:
  16.     print '"%s" is not a palindrome' % phrase1

  17. print

  18. phrase2 = "Madam in Eden I'm Adam"
  19. if isPalindrome(phrase2):
  20.     print '"%s" is a palindrome' % phrase2
  21. else:
  22.     print '"%s" is not a palindrome' % phrase2
阅读(2028) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~