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
--
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:
- You pass
abcbatoisPalindrome isPalindromecallsisPal(toChars(s))toChars(s)returns"abcba"so this is passed toisPal(..)isPalis called with the argument"abcba".- Check: is
len(s)<=1? No,len(s)is5. - So to
else: iss[0] == s[-1]? Yes. If it wasn't, this function would stop right here and returnFalse. But now to the next step. - Since
s[0] == s[-1]isTruewe need to evaluateisPal(s[1:-1]). Keep in mind, thats[1:-1]is now"bcb". So runisPal("bcb").len("bcb")is3so go toelse.s[0] == s[-1]isTrue. EvaluateisPal(s[1:-1])wheres[1:-1]now is"c".len(s)is1, therefore:return True
isPal(s[1:-1])returnedTruesos[0] == s[-1] and isPal(s[1:-1])isTrue. ReturnTrue.
isPal(s[1:-1])returnedTruesos[0] == s[-1] and isPal(s[1:-1])isTrue.isPal(toChars(s))returnsTrue: 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.