Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking out of a recursive function?

Tags:

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")
like image 224
Chris Avatar asked May 11 '12 02:05

Chris


People also ask

Can we stop recursion using break?

At some point all recursive paths should break. Otherwise it will be an infinite recursion and stack overflow exception occurs.

How do you break a recursive function in C++?

There's no way to break out of a recursive function, at least not in the same sense as with loops.


1 Answers

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.

like image 172
li.davidm Avatar answered Sep 21 '22 18:09

li.davidm