# math_recursion.py # Walker M. White (wmw2), Lillian Lee (LJL2) # September 9, 2012 """A module of recursive mathematical functions.""" def factorial(n): """Returns: n! Precondition: n is a nonnegative integer""" assert type(n) == int, `n`+' is not an int' # get in the habit assert n >= 0, `n`+' is negative' # get in the habit if n==0: # Base case return 1 # Recursive case. return n*factorial(n-1) def fibonacci(n): """Returns: the nth Fibonacci number a_n = a_{n-1}+a_{n-2} Precondition: n is a nonnegative integer""" assert type(n) == int, `n`+' is not an int' # get in the habit assert n >= 0, `n`+' is negative' # get in the habit if (n==0 or n==1): # Base cases return 1 # Recursive case. return fibonacci(n-1)+fibonacci(n-2)