An example of a situation where it is much more intuitive to use a recursive algorithm would be when implementing a program to calculate the n-th Fibonacci number. For those who never heard about it before, the Fibonacci numbers are a sequence of integers where each number is the sum of the two preceding numbers from the sequence. So the sequence goes on like this 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
I quickly implemented a program to calculate the nth fibonacci number:
def fib(n):
if n <= 1:
return n
else:
return fib(n-2) + fib(n-1)
But if I had insisted on not using recursion, the code would have been much more complicated, while not having any advantage over the recursive code:
def fib(n):
if (n <= 1):
return n
current = 1
previous = 1
for i in range(2, n + 1):
temp = current
current += previous
previous = temp
return temp
As you can see, the recursive example is much easier to understand(and much cleaner) in this case.
No comments:
Post a Comment