0

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
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Eric R.
  • 5
  • 2
  • 1
    I’m completely with you that the factorial example of recursion could be replaced with a simpler and faster iterative version. Other recursive algorithms - recursive sorting algorithms like quicksort or mergesort, recursive searching algorithms like depth-first search or median-of-medians, and backtracking searches like the ones used to solve Sudokus - are much harder to convert to iterative solutions. Independently, learning to think recursively is a great way to train yourself to look at problems in different ways. So yes - it’s a useful skill, though I’m with you about factorials. :-) – templatetypedef Nov 30 '19 at 03:08
  • Another great example is computing fibonacci numbers! It is much easier through recursion than through iterative methods. – James Mchugh Nov 30 '19 at 05:48

1 Answers1

1

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

Tobias S
  • 79
  • 7