Recursion is very deceiving. It looks simple but it is anything but from the computer's standpoint, being very resource intensive. Yes, it is important to understand recursive functions, how they work and how to write them. Just don't be fooled into thinking them simple. There is a reason they are not discussed in these introductory tracks. In most cases, we can write an algorithm that is comparably fast, or faster, and in most cases more efficient.

Take a gander at this post I compared several factorial functions to see how fast they were.

Just for fun @jirapong_p I will add your time to this post, I had to change the max recursion depth because of your code though.

CODE:

import sys
import cProfile
sys.setrecursionlimit(20000)
def factorial(x):
if x == 0 or x == 1:
return 1
else:
return (x * factorial(x - 1))
def cf_range(num_range):
"""
This function saves the factorial to file. It also calls the function
ranging from 1 to the given number. So all factorials to the number are
saved to file. The computer has problems displaying any number
the system can not handle.
:param num_range: Range of numbers to be factored
"""
with open("factorial_of_%s.txt" % str(num_range), "w+") as file:
for number in range(1, num_range + 1):
file.write(str(factorial(number)) + "\n")
cProfile.run("cf_range(5000)")

As you can see you had 10 million function calls with your 4500 recursive function calls in 50.3 secs which vs my code at

So as you can see the larger the number gets the more time effective my code gets, while my code

Is quite a bit faster than yours even though you have a very succinct code. If you do not get some of my code ask away and I will try to explain it best as I am able.

lol I didn't think of that but you would need to edit the z.append(y) to be z.append(y+1). Remember python always starts counting at 0 and if you multiply by 0 you get 0.

heres the updated code.

import operator
def factorial(x):
z=[]
for y in range(x):
z.append(y+1)
return reduce(operator.mul, z)

I'm trying to visualize this....is this kind of like Inception (a function within a function within a function)? So you keep stepping into another factorial function ( in -1 increments) and once you return 1 it reiterates backwards and performs the multiplication? If anyone could explain the exact steps here, it would be much appreciated.