python:递归检查以确定字符串是否为回文 [英] python: recursive check to determine whether string is a palindrome

查看:91
本文介绍了python:递归检查以确定字符串是否为回文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是定义一个过程 is_palindrome,它将一个字符串作为输入,并返回一个指示输入字符串是否为回文的布尔值.在这种情况下,单个字母应返回 True,空字符串 '' 也应返回 True.

My task is to define a procedure is_palindrome, that takes as input a string, and returns a boolean indicating if the input string is a palindrome. In this case a single letter should return True, as should an empty string ''.

很遗憾,我没有得到预期的结果.我很感激你的帮助.

Unfortunately, I'm not getting the expected results. I appreciate the help.

我的代码版本 1:

def is_palindrome(s):
    if s == '':
        return True
    else:
        if (ord(s[0]) - ord(s[len(s)-1])) == 0:
            is_palindrome(s[1:len(s)-1])
        else:
            return False

print is_palindrome('')
#>>> True    (expected = True)

print is_palindrome('abab')
#>>> False    (expected = False)

print is_palindrome('abba')
#>>> None    (expected = True)

print is_palindrome('andrea')
#>>> None    (expected = False)

print is_palindrome('abaaba')
#>>> None    (expected = True)

我通过调试器跟踪了我的代码,看起来逻辑是正确的,因为代码采用了适当的路径.但是,对于上面突出显示的某些情况,最终结果似乎切换为无".

I followed my code through the debugger and it seems the logic is correct as the code takes the appropriate path. However, the end result seems to switch to 'None' for some of the cases as highlighted above.

如果我将代码更改为以下内容:

If I change my code to the following:

我的代码版本 2:

def is_palindrome(s):
        if s == '':
            result = True
        else:
            if (ord(s[0]) - ord(s[len(s)-1])) == 0:
                is_palindrome(s[1:len(s)-1])
            else:
                result = False
        return result

print is_palindrome('')
#>>> True    (expected = True)

print is_palindrome('abab')
#>>> False    (expected = False)

print is_palindrome('abba')
#>>> Error    (expected = True)
UnboundLocalError: local variable 'result' referenced before assignment 

print is_palindrome('andrea')
#>>> Error   (expected = False)         
UnboundLocalError: local variable 'result' referenced before assignment

print is_palindrome('abaaba')
#>>> Error    (expected = True)
UnboundLocalError: local variable 'result' referenced before assignment

推荐答案

在您的第一个示例中,您忘记了 return 语句:

In your first example, you forgot a return statement:

def is_palindrome(s):
    if s == '':
        return True
    else:
        if (ord(s[0]) - ord(s[len(s)-1])) == 0:
            # v-- forgot this here
            return is_palindrome(s[1:len(s)-1])
        else:
            return False

这篇关于python:递归检查以确定字符串是否为回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆