Breaking out of a recursive function?
python, recursion
Solution
def is_pal(string):
if len(string) <= 1:
return True
if first(string) == last(string):
return is_pal(middle(string))
else:
return False
That way, if they don't match, `False` is returned; if it makes it all the way to the end, True is returned. I also eliminated a redundant conditional and checked for the edge-case of an even-length palindrome.
Problem
I'm wondering how to break out of a recursive loop to the main function. I am trying to do a simple palindrome exercise. The function should return True for `"redivider"` but the `return True` is being passed to `is_pal()` and the function isn't breaking. Short of adding a second variable to `is_pal` to track True/False, what is the proper way to break out of this recursive loop? ``` def first(word): return word[0] def last(word): return word[-1] def middle(word): return word[1:-1] def is_pal(str): if len(str) == 1: return True if first(str) == last(str) and len(str) > 1: is_pal(middle(str)) print is_pal("redivider") ```