1. Factorial and Fibonacci using Python
Given the code provided in the lecture slides, implement the
iterative and recursive
functions for Factorial and Fibonnaci. with Wrappers and
Exceptions.
Investigate their performance by running them with increasing
values for n. How
high can you go?
----
def calcNFactorialRecursive( n ):
factorial = 1 declare and initialise local variable
if ( n == 0 ): Simplest case (the ‘base case’)
factorial = 1 no more multiple returns!
else:
factorial = n * calcNFactorialRecursive( n-1 ) Recursive call
return factorial return local variable
----------------------
• Iterative solution using for loop
def calcNFactorial( n ):
nFactorial = 1
for ii in range( n, 1, -1 ):
nFactorial = nFactorial * ii
return nFactorial
• Recursive solution is to solve (N-1)! and multiply by N
def calcNFactorialRecursive( n ):
if ( n == 0 ): Simplest case (the ‘base case’)
return 1 oops – multiple returns!
else:
return n * calcNFactorialRecursive( n-1 ) Recursive call multiplied
by n,
n changed to go towards base case
*******
Recursive solution:
def fibRecursive( n ):
fibVal = 0
----
• Iterative solution:
def fibIterative( n ):
fibVal = 0 value n
currVal = 1 value n-1
lastVal = 0 value n-2
if (n == 0):
fibVal = 0
else if (n == 1):
fibVal = 1
else:
for ii in range(2, n):
fibVal = currVal + lastVal
lastVal = currVal set up lastVal and currVal ready for next
iteration
currVal
----------------------
if (n == 0):
fibVal = 0 Base case #1
else if (n == 1):
fibVal = 1: Base case #2
else:
fibVal = fibRecursive(n-1) + fibRecursive(n-2) Two recursive
calls
return fibVal
Compare with Mathematical Definition
FIB 0 = 0, FIB 1 = 1, FIB N = FIB (N-1) + FIB (N-2)
1. Factorial and Fibonacci using Python Given the code provided in the lecture slides, implement the iterative and recur
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am