Skip to main content
 首页 » 编程设计

python之Python中最长的回文

2025年05月04日14lvdongjie

我有一个 Python 作业要求我编写一个程序来查找给定文本中的最长回文。我知道这个网站上有其他语言的这个函数的例子,但我是 Python 的初学者并且在编写代码时遇到了麻烦。

这就是我目前识别回文的方式:

def is_palindrome(word): 
    x = 0  
    for i in range (len(word)/2): 
        if (word[x]) == (word[len(word)-x-1]): 
            x+=1 
        if x == (len(word)/2): 
            return True 
    return False 

请您参考如下方法:

替代方式

def Is_palindrome(word): 
       return word==word[::-1] 
# Assuming text is defined 
print max((word for word in set(text.split()) if Is_Palindrome(word)), key=len)