Reputation: 5
Are there any useful cases of recursion? I am beginning to learn recursion and came across an example of using recursion for factorial of a number.
def factorial(num):
if num == 1:
return 1
else:
return num * factorial(num - 1)
However, it can be done without recursion and would be faster when timed...
def fact(num):
lst = []
number = num
for i in range(1,num):
lst.append(i)
for i in lst:
number = number * i
return number
Upvotes: 0
Views: 36
Reputation: 89
The point is usually for the sake of simplicity. Yes you could convert them to iterative versions for the sake of improving run time, but this would make them much less readable.
This thread sums it up pretty well: what is recursion and when should I use it
Upvotes: 1