Python中最长的回文

时间:2015-03-24 03:47:53

标签: python

我有一个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

3 个答案:

答案 0 :(得分:4)

替代方式

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)

答案 1 :(得分:1)

我用过:

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 longest_palindrome(text):
    lst = text.split() #Split it into words (cannot have punctuation)
    palindromes = [] #List that contains the palindromes
    long_len = 0 #Length of the longest palindrome
    longest = "" #The actual longest palindrome
    for i in lst: #Loop through all the words
        if Is_palindrome(i): #If the word is a palindrome
            palindromes.append(i) #Add it to the palindrome list
    for i in palindromes: #Loop through the palindrome list
        if len(i) > long_len: #If the palindrome is longer than the longest one
            longest = i #Set it as the longest one
            longest_len = len(i) # Set the length of the longest one to the length of this one
    return longest

答案 2 :(得分:1)

def fastLongestPalindromes(seq):
    seqLen = len(seq)
    l = []
    i = 0
    palLen = 0
    while i < seqLen:
        if i > palLen and seq[i - palLen - 1] == seq[i]:
            palLen += 2
            i += 1
            continue
        l.append(palLen)
        s = len(l) - 2
        e = s - palLen
        for j in range(s, e, -1):
            d = j - e - 1
            if l[j] == d: 
                palLen = d
                break
            l.append(min(d, l[j]))
        else:
            palLen = 1
            i += 1
    l.append(palLen)
    lLen = len(l)
    s = lLen - 2
    e = s - (2 * seqLen + 1 - lLen)
    for i in range(s, e, -1):
        d = i - e - 1
        l.append(min(d, l[i]))

    return l
def getPalindrome(text):
    lengths = fastLongestPalindromes(text)
    start = 0
    end = 0
    length = 0
    for i in range(len(lengths)):
        if(lengths[i] > length):
            length = lengths[i]
            end = i//2+(lengths[i]//2)
            start = i//2-(lengths[i]//2)
            if(i%2 == 1):
                start +=1
    return text[start:end]

在线性时间。 (代码越长,但比其他答案更快,至少是长串)。

来源:http://www.akalin.cx/longest-palindrome-linear-time(第一个功能是复制粘贴)