#---------------------------------------------------------------------- # Discussion of iteration vs. recursion. # Copyright (C) March 24, 2017 -- Dr. William T. Verts # # Recursion is "divide and conquer" - breaking a bigger problem # down into smaller and smaller chunks until each chunk is small # enough to solve on its own, then "unwinding" back, reassembling # the pieces until the original problem has been solved. #---------------------------------------------------------------------- #---------------------------------------------------------------------- # EXAMPLE #1 # I want to enter a integer N, compute the factorial of N. # N! = 1*2*3*4* ... *N # 0! = 1 #---------------------------------------------------------------------- # Non-Recursive (Iterative) Method # Requires several local variables and an explicit loop. # Very fast. def Factorial1 (N): F = 1 for I in range(1,N+1): F = F * I return F # Recursive Method # # Notice that N! = N * (N-1)! # That is, I don't know how to solve N!, but I # can figure it out if I can compute (N-1)!, # which is a smaller problem. # # The "loop" is formed from the recursive calls. # Simple and elegant definition of the problem, # but calling with large N creates a large stack # of deferred environments that must be "unwound". def Factorial2 (N): if (N <= 1): return 1 else: return N * Factorial2(N-1) #---------------------------------------------------------------------- # EXAMPLE #2 # The Fibonacci sequence is defined as starting with 0 and 1, # and then each new value is the sum of the previous two. # Occurs in nature and many places in math. # # Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34 55 ... # # Ratio of successive pairs of numbers from the sequence # converges on the Golden Mean: F(N)/F(N-1) --> 1.618... # # Parameter N says which Fibonacci number is returned: # N F(N) # 0 0 # 1 1 # 2 1 # 3 2 # 4 3 # 5 5 # 6 8 # 7 13 # ... ... #---------------------------------------------------------------------- # The recursive version is EXTREMELY elegant and simple to write, # but takes an ENORMOUS amount of time for large N. def Fibonacci1 (N): if (N == 0): return 0 if (N == 1): return 1 return Fibonacci1(N-1) + Fibonacci1(N-2) # The iterative method is considerably more # complicated but is also significantly faster. def Fibonacci2 (N): if (N == 0): return 0 if (N == 1): return 1 F0 = 0 F1 = 1 for I in range(2,N+1): F2 = F0 + F1 F0 = F1 F1 = F2 return F2 # For comparison purposes, try: # Fibonacci1(35) # Fibonacci2(35) # You'll notice that the recursive # approach takes a noticeable amount # of time (several seconds), while the # iterative approach is nearly instantaneous.