2017-07-28 78 views
-3

输出字符串是否是回文输出测试字符串是否是回文测试

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') 

执行功能“testIspalindrome1()”,将得到以下结果:

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 

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

+1

'def isPalindrome1(s):return s [:: - 1] == s' –

+1

什么是“秃头字母”?我不明白这个问题。 – Prune

+0

@Prune大胆。错字 –

回答

0

逻辑:

  • 减少原始输入只有小写字母
  • 是最终的信件一样吗?如果不是,这不是回文。
  • 如果它们匹配,那么这是一个潜在的回文。
  • 剥离结束字母;在剩余的字符串上重复。
  • 如果你用完字母来匹配,这是一个回文:所有的目标都匹配起来。

这是说明你的逻辑吗?

后面来从基础CASE

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 

...等等,直到我们到达原来的呼叫。

+0

“关于为gg返回True”我不明白递归如何得到这个结果。 – larry

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 
+0

“关于返回真的gg”我不明白如何递归得到这个结果。 – larry

+0

尤其适用于“s ='gg'” – larry

+0

然后写在纸上。你知道'[1:-1]'在做什么吗? –

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

相关问题