python - Output of testing if string is Palindrome -
output of testing if string palindrome
def ispalindrome1(s): """assume s str returns true if s palindrome;false otherwise. punctuation marks, blanks, , capitalization ignored.""" def tochars(s): s = s.lower()# means:s = 'abcd',if s referenced s.lower,then s='abcd'. ans = '' 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 ' return true base case' return true else: ans = s[0] == s[-1] , ispal(s[1:-1]) print ' return',ans,'for',s return ans return ispal(tochars(s)) def testispalindrome1(): print 'try doggod' print ispalindrome1('doggod') print 'try dogood' print ispalindrome1('dogood')
execute function "testispalindrome1()" following result:
try doggod ispal called doggod ispal called oggo ispal called gg ispal called **about return true base case return true gg return true oggo return true doggod** true try dogood ispal called dogood ispal called ogoo ispal called go return false go return false ogoo return false dogood false
what's logic of execution on section in stars?
everytime recursion returned from, must continue method called.
ans = s[0] == s[-1] , ispal(s[1:-1]) # branches off, other function call print ' return',ans,'for',s # waits recursion finish
Comments
Post a Comment