用字符串切片实现回文(palindrome)判断

 好神奇,这样都可以实现。
# 步长为-1 表示切片按照相反的方向访问字符串,所以切片[::-1]会得到一个逆序的字符串。



def is_palindrome(string):
    if string == string[::-1]:
        return True
    return False

print(is_palindrome('abcbc'))
print(is_palindrome('abcba'))

《像计算机科学家一样思考Python》练习8-3

以下这部分是转载自网址

http://greenteapress.com/thinkpython2/code/palindrome_soln.py

《像计算机科学家一样思考Python》练习6-3

def first(word):
    """Returns the first character of a string."""
    return word[0]


def last(word):
    """Returns the last of a string."""
    return word[-1]


def middle(word):
    """Returns all but the first and last characters of a string."""
    return word[1:-1]


def is_palindrome(word):
    """Returns True if word is a palindrome."""
    if len(word) <= 1:
        return True
    if first(word) != last(word):
        return False
    return is_palindrome(middle(word))


print(is_palindrome('allen'))
print(is_palindrome('bob'))
print(is_palindrome('otto'))
print(is_palindrome('redivider'))

猜你喜欢

转载自blog.csdn.net/sisqzy86/article/details/82750133