The Python Oracle

Recursion on string: What does the line 'return s[0] == s[-1] and isPal(s[1:-1])' do?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Breezy Bay

--

Chapters
00:00 Question
01:59 Accepted answer (Score 1)
03:20 Thank you

--

Full question
https://stackoverflow.com/questions/5316...

Accepted answer links:
[here]: https://docs.python.org/3/library/stdtyp...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #recursion

#avk47



ACCEPTED ANSWER

Score 1


Well you have to think through this step by step:

  1. You pass abcba to isPalindrome
  2. isPalindrome calls isPal(toChars(s))
  3. toChars(s) returns "abcba" so this is passed to isPal(..)
  4. isPal is called with the argument "abcba".
  5. Check: is len(s)<=1? No, len(s) is 5.
  6. So to else: is s[0] == s[-1]? Yes. If it wasn't, this function would stop right here and return False. But now to the next step.
  7. Since s[0] == s[-1] is True we need to evaluate isPal(s[1:-1]). Keep in mind, that s[1:-1] is now "bcb". So run isPal("bcb").
    1. len("bcb") is 3 so go to else.
    2. s[0] == s[-1] is True. Evaluate isPal(s[1:-1]) where s[1:-1] now is "c".
      1. len(s) is 1, therefore: return True
    3. isPal(s[1:-1]) returned True so s[0] == s[-1] and isPal(s[1:-1]) is True. Return True.
  8. isPal(s[1:-1]) returned True so s[0] == s[-1] and isPal(s[1:-1]) is True.
  9. isPal(toChars(s)) returns True: You have a palindrome!

Hope this makes it clearer for you.

EDIT Step 6 does always come before Step 7 because Python explicitly goes from left to right in logical expressions, see here. If this does not happen, your interpreter is broken.