A few days ago someone said to me that recursion would be better then iteration and should, if possible, always be used.
So, I dove into recursion and tried writing a simple program to get the factorial of a number. This is the recursion:
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
and although this works fine, it gets a RuntimeError: maximum recursion depth exceeded
as soon as n
gets above 997.
So I wrote a simple function that does exactly the same, but with a for loop
.
def fact(n):
a = 1
for x in range (0, n, 1):
a = a * (n - x)
return a
while n < 10000
it gives the answer within 150ms.
So, I though maybe recursion is faster with low numbers, but nope. It takes longer:
So my question is:
Is there any reason at all to use recursion when writing programs in Python?
and:
Are there any problems that can only be solved with recursion?