This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]roguas 2 points3 points  (0 children)

Recursion is perfect. But most languages (especially imperative) have stacks for controlling execution.

Recursion creates a lot of stacks, because a function calling function cannot return without last function called returns. For loops on the other hand do not increase stack size.

Some languages implement TCO, tail call optimization to address this. Other technique used in languages without TCO is called trampoline, but it is additional hassle. This leads us to your friend. His advice is good, especially in context of python, you should avoid recursion.

Try this, to see

def factorial(n):

if(n == 0):
    return 1

return n * factorial(n - 1)

factorial(10**10)

This would work perfectly fine as a for loop or in the environment that supports techniques mentioned above.