I watched a video a couple of hours ago on recursion in python and then recreated the program which was made in the video so it worked in my version of Python. The code works but there is a bit I don't understand fully and what it is doing.
def lower(s):
s = s.lower()
return s
def isPal(s):
if len(s) <= 1:
return True
else:
return s[0] == s[-1] and isPal(s[1:-1])
def isPalindrome(s):
if isPal(lower(s)) == True:
print("{0} is a palindrome".format(s))
The part which I am having an issue with is the
return s[0] == s[-1] and isPal(s[1:-1])
What I am wondering is why are they being returned and also why is it s[1:-1] and not s[0:-1] if you think you know of any good places which would help simplify recursions for me feel free to share them. Thanks in advance.
why is it s[1:-1] and not s[0:-1]
s[1:-1] returns s with the first and last element chopped off. s[0:-1] returns s with just the last element chopped off.
You need to chop off both ends to preserve the palindrome property (if it is a palindrome), which is that elements equidistant from the middle are identical. If you chop off only one end, you move the middle, which would (in the general case) destroy that invariant.
This goes to the heart of self recursion: you do a thing, then you delegate a simpler case which has the same properties.
Why return s[0] == s[-1] and isPal(s[1:-1])
This is being returned because it first checks that the first and last elements have the palindrome property (as above) AND that the next "layer" also has that property. If the outer pair is not equal it is not a palindrome, and False will be returned; if it is true, the recursive step is taken, and if that is True, the expression as a whole returns True.
Imagine you have the word 'kayak'
The program will look if :
'k' == 'k' if yes the program will call the function with : 'aya'
Then the program will look if 'a' == 'a' if yes the program will call the function with 'y'
Then it's only one letter, So the program returns True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With