pythonrecursion

Is it bad practice to use Recursion where it isn't necessary?


In one of my last assignments, I got points docked for using recursion where it was not necessary. Is it bad practice to use Recursion where you don't have to?

For instance, this Python code block could be written two ways:

def test():
    if foo() == 'success!':
        print(True)
    else:
        test()

or

def test():
    while True:
        if foo() == 'success!':
            print(True)
            break

Is one inherently better than another? (Performance-wise or Practice-wise)?


Solution

  • While recursion may allow for an easier-to-read solution, there is a cost. Each function call requires a small amount of memory overhead and set-up time that a loop iteration does not.

    The Python call stack is also limited to 1000 nested calls by default; each recursive call counts against that limit, so you risk raising a run-time error with any recursive algorithm. There is no such hard limit to the number of iterations a loop may make.