The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles

--

Chapters
00:00 Recursion On String: What Does The Line 'Return S[0] == S[-1] And Ispal(S[1:-1])' Do?
01:29 Accepted Answer Score 1
02:08 Thank you

--

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

--

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.