如果字符串是Palindrome,则输出测试

时间:2017-07-28 00:15:00

标签: python recursion

如果字符串是Palindrome

,则输出测试
def isPalindrome1(s):
    """Assume s is an str
       Returns True if s is a palindrome;False otherwise.
         Punctuation marks, blanks, and capitalization are
         ignored."""
    def toChars(s):
        s = s.lower()# Means:s = 'ABCD',if s referenced by s.lower,then s='abcd'.
        ans = ''
        for c in s:
            if c in'abcdefghijklmnopqrstuvwxyz':
                ans =ans+c
        return ans

    def isPal(s):
        print ' isPal called with',s
        if len(s)<=1:
            print ' About to return True from base case'
            return True
        else:
            ans = s[0] == s[-1] and isPal(s[1:-1])
            print ' About to return',ans,'for',s
            return ans 

    return isPal(toChars(s)) 

def testIspalindrome1():
    print 'Try dogGod'
    print isPalindrome1('dogGod')
    print 'Try doGood'
    print isPalindrome1('doGood')

执行函数&#34; testIspalindrome1()&#34;将得到以下结果:

Try dogGod
 isPal called with doggod
 isPal called with oggo
 isPal called with gg
 isPal called with 
 **About to return True from base case
 About to return True for gg
 About to return True for oggo
 About to return True for doggod**
True
Try doGood
 isPal called with dogood
 isPal called with ogoo
 isPal called with go
 About to return False for go
 About to return False for ogoo
 About to return False for dogood
False

星星部分的执行逻辑是什么?

3 个答案:

答案 0 :(得分:1)

每次返回递归时,都必须从调用方法的地方继续。

ans = s[0] == s[-1] and isPal(s[1:-1])  # This branches off, like any other function call 
print ' About to return',ans,'for',s  # This waits for recursion to finish 

答案 1 :(得分:0)

逻辑:

  • 将原始输入简化为小写字母
  • 结尾字母是否相同?如果没有,这不是回文。
  • 如果匹配,那么这是一个潜在的回文。
  • 剥去末尾字母;重复剩余的字符串。
  • 如果你的信件用完了,它就是一个回文:所有的结局都匹配了。

这能为你解释逻辑吗?

从基础案例回来

About to return True for gg来自此代码:

ans = s[0] == s[-1] and isPal(s[1:-1])
print ' About to return',ans,'for',s

让我们看看赋值中的表达式,用它们的值替换符号:

ans = "g" == "g" and True

我们从最后的递归调用中得到最后的True,其中参数是空字符串。基本案例返回True,我们在这里使用。 结束字母匹配,中间字母(空字符串)形成回文,因此完整字符串也是回文。因此,我们会将True返回到上一个电话。

此调用现在使用字符串oggo进行相同的处理:

and = "o" == "o" and True

......等等,直到我们到达原来的电话。

答案 2 :(得分:0)

 **About to return True from base case
 About to return True for gg
 About to return True for oggo
 About to return True for doggod**

这样可以保持从正面和背面移除角色。 并继续检查pallindrome