回文算法和UnboundLocalError

Palindrome Algorithm and UnboundLocalError

这是我用于查找字符串中最长回文的代码。 我收到以下错误消息: "UnboundLocalError: local variable 'Current_Pal' referenced before assignment"

我知道变量“Current_Pal”应该在 isPal 函数中,但如果我这样做,变量将在每个循环中初始化为零。

def isPalindrome(s):
    Current_Pal = ''
    Longest_Pal = ''

    def toChars(s):
       s = s.lower()
       ans= ''
       for c in s:
           if c in 'abcdefghijklmnopqrstuvwxyz':
                ans = ans+ c
       return ans

    def isPal(s):
        if len(s) <= 1:
             return Current_Pal + s
        else:
            if s[0] == s[-1]:
                Current_Pal = Current_Pal + s[0]

        else:
            if Current_Pal > Longest_Pal:
                Longest_Pal = Current_Pal
                Current_Pal = ''
        return isPal(s[1:-1])
return isPal(toChars(s))

Palin = isPalindrome("HYTBCABADEFGHABCDEDCBAGHTFYW1234567887654321ZWETYGDE")
print(Palin)

你有一个递归函数,所以你需要传入一个初始值 Current_Pal 并继续将该变量传递给后续调用;您也可以对 Longest_Pal 执行相同的操作,如下所示:

def isPal(s, Current_Pal='', Longest_Pal=''):
    if len(s) <= 1:
         return Current_Pal + s
    else:
        if s[0] == s[-1]:
            Current_Pal = Current_Pal + s[0]

    else:
        if Current_Pal > Longest_Pal:
            Longest_Pal = Current_Pal
            Current_Pal = ''
    return isPal(s[1:-1], Current_Pal, Longest_Pal)

这样它被设置为 '' 然后额外的变化不断地传递到方法中,保留它以前的值。

附带说明一下,您可能应该重写您的 else 语句:

def isPal(s, Current_Pal='', Longest_Pal=''):
    if len(s) <= 1:
         return Current_Pal + s
    elif s[0] == s[-1]:
            Current_Pal = Current_Pal + s[0]
    elif Current_Pal > Longest_Pal:
            Longest_Pal = Current_Pal
            Current_Pal = ''
    return isPal(s[1:-1], Current_Pal, Longest_Pal)