发上等愿,结中等缘,享下等福;择高处立,寻平处住,向宽处行

Brick walls are there for a reason :they let us prove how badly we want things

代码改变世界

python 判断回文字符串的方法

2019-05-06 15:32  kowme  阅读(7102)  评论(0编辑  收藏  举报
# -*- coding:utf-8 -*-

# palindrome str : 回文字符串:一个字符串,不论是从左往右,还是从右往左,字符的顺序都是一样的(如abba,等)


def is_palindrome_1(tmp_str):
    for i in range(len(tmp_str)):
        if tmp_str[i] != tmp_str[-(i+1)]:
            return False
    return True


def is_palindrome_2(tmp_str):
    # tmp_str_reverse = tmp_str[::-1]
    # if tmp_str == tmp_str_reverse:
    #     return True
    # else:
    #     return False
    return tmp_str == tmp_str[::-1]


#递归
def is_palindrome_3(tmp_str):
    if len(tmp_str) <= 1:
        return True
    else:
        if tmp_str[0] == tmp_str[-1]:
            return is_palindrome_3(tmp_str[1:-1])
        else:
            return False


if __name__ == "__main__":
    test_str1 = "abcba"
    test_str2 = "123456a"
    print is_palindrome_1(test_str1)
    print is_palindrome_2(test_str1)
    print is_palindrome_3(test_str1)

    print is_palindrome_1(test_str2)
    print is_palindrome_2(test_str2)
    print is_palindrome_3(test_str2)

  

It's not who you are underneath, it's what you do that defines you

Brick walls are there for a reason :they let us prove how badly we want things