I am currently going through 6.00.1x with MITx and recursion of string, but the following code really confuses me. This is supposed to tell whether a string is a palindrome (one which reads the same backward as forward), with abcba as a test string I use:
def isPalindrome(s):
def toChars(s):
s = s.lower()
ans = ''
for c in s:
if c in 'abcdefghijklmnopqrstuvwxyz':
ans = ans + c
return ans
def isPal(s):
if len(s) <= 1:
return True
else:
return s[0] == s[-1] and isPal(s[1:-1])
return isPal(toChars(s))
isPalindrome('abcba')
The line return s[0] == s[-1] and isPal(s[1:-1]) really confuses me: I ran it on Python Tutor and it seems that upon running this line the first time, it goes recursively first, ie cutting out bcb and c, then as c would be the base case, it returns true and likewise for bcb.
2 things I am confused:
Why does it go recursively the first time when it runs this line of code?
s[0] == s[-1]should return a Boolean value T/F, but this seems to have been ignored till it reaches the base case?So the recursion runs till it reaches the base case - that I get, but then the s[0] == s[-1] doesn't start running only till it reaches here...why? And how did the syntax of the code instruct the computer to evaluate s[0] == s[-1] on bcb?