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")
                At some point all recursive paths should break. Otherwise it will be an infinite recursion and stack overflow exception occurs.
There's no way to break out of a recursive function, at least not in the same sense as with loops.
def is_pal(str):    
    if len(str) <= 1: 
        return True
    if first(str) == last(str): 
        return is_pal(middle(str))
    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.
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