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

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

代码改变世界

python 判断回文字符串的方法

  kowme  阅读(7123)  评论(0编辑  收藏  举报
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# -*- 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)

  

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架

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

点击右上角即可分享
微信分享提示