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
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:
- 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.