pythonrecursioniteration

How should I convert this recursive function into iteration?


I have a recursive function in the following form:

def f():
    if cond1:
        ...
        f()
    elif cond2:
        ...

I've "mechanically" converted it to an iterative function like this:

def f():
    while True:
        if cond1:
            ...
        elif cond2:
            ...
            break
        else:
            break

I believe this conversion is valid, but is there a more elegant way to do it? For example, one that doesn't need multiple break statements?


Solution

  • Since the loop effectively continues only when cond1 is met, you can make it the condition that the while loop runs on, and run the code specific to cond2 after the loop if it's met:

    def f():
        while cond1:
            ...
        if cond2:
            ...