Chinaunix首页 | 论坛 | 博客
  • 博客访问: 367036
  • 博文数量: 97
  • 博客积分: 2846
  • 博客等级: 少校
  • 技术积分: 1000
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-19 20:00
文章分类

全部博文(97)

文章存档

2017年(1)

2013年(2)

2012年(6)

2011年(17)

2010年(12)

2009年(41)

2007年(18)

我的朋友

分类: Python/Ruby

2009-04-04 20:10:55

参考:
 
输入一段序列,判断该序列是否为回文
1,分别从左到右、从右到左判断字符是否相等。
 
 

def is_palindrome(text):

    p1 = 0
    p2 = len(text) - 1
    t = text.lower()
    while p1 < p2:

        if not text[p1].isalnum():
            p1 += 1

        elif not text[p2].isalnum():
            p2 -= 1

        else:
            print t[p1],t[p2]
            if t[p1] != t[p2]:
                return False
        p1 += 1
        p2 -= 1

    return True

if is_palindrome(raw_input("Input sentence: ")):
    print "Palindrome!"

 

2,直接将整个序列反转,判断源序列和反转后的序列是否相等

 

s = raw_input("Sentence? ").replace(" ", "").lower()

if s == s[::-1]:
    print "Your sentence is a palindrome"
else:
    print "Not a palindrome"

阅读(1050) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~