Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 8 Online
OpenStudy (anonymous):

def isPal(s): if len(s) <= 1: return True else: return s[0] == s[-1] and isPal(s[1:-1]) now this is a problem from the lecture of recursion... my doubt is.. how is the function ispal being incremented each time... we are not appending or deleting anything from the string s???

OpenStudy (anonymous):

http://dpaste.com/1034508/ line 5 is a little tricky. it is taking advantage of Pythons lazy evaluation, or 'short circuit' behaviour. when Python evaluates "A and B": - if A evaluates as False then B is never evaluated and the value of the expression is False - if A evaluates as True then B is evaluated and if B evaluates as True then the value of the entire expression takes on the value of B in this function, line 5 works like this: s[0] == s[-1] : if the first and last letters are different then return False if the first and last letters are the same then evaluate the right side of the expression isPal(s[1:-1]): this calls isPal() with the first and last letters of the string removed this is a recursive process as well as a recursive procedure - it 'builds up' a series of 'True and return_value_of_recursive_call' expressions on the call stack. when the last function called returns (True or False) without recursing, each function in turn completes the expression and returns to the function that called it. hope that made sense. adding print statements help - http://dpaste.com/1034528/ this is a great tool to see what happens when your code executes: http://www.pythontutor.com/visualize.html#code=def+isPal(s,+n%3D0)%3A%0A++++print+'function+%23',+n,+'%5Cts%3A',+s%0A++++if+len(s)+%3C%3D+1%3A%0A++++++++return+True%0A++++else%3A%0A++++++++return+s%5B0%5D+%3D%3D+s%5B-1%5D+and+isPal(s%5B1%3A-1%5D,+n%2B1)%0A++++%0Aprint+isPal('abcdefghgfedcba')&mode=display&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&py=2&curInstr=0

OpenStudy (anonymous):

http://www.pythontutor.com/

OpenStudy (anonymous):

thanks for the help!!!... :) :)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!