'''Some simple recursive functions. Jeff Ondich, 12 Feb 2007 These functions illustrate some simple recursion. ''' def iterativeFactorial(n): ''' Returns the factorial of the integer n (or 1 if n is less than zero). ''' print 'iterativeFactorial:', n product = 1 for k in range(2, n + 1): product = product * k return product def recursiveFactorial(n): ''' Returns the factorial of the integer n. ''' print 'recursiveFactorial:', n if n == 1: print 'recursiveFactorial ending:', n, 1 return 1 result = n * recursiveFactorial(n - 1) print 'recursiveFactorial ending:', n, result return result def iterativeFibonacci(n): ''' Returns the nth Fibonacci number. Note that n should start counting at 1, so 1 1 2 3 5 8 are the first through sixth Fibonacci numbers (not the zeroth through fifth). ''' previous = 1 current = 1 for k in range(n-2): next = current + previous previous = current current = next return current def recursiveFibonacci(n): ''' Returns the nth Fibonacci number. Note that n should start counting at 1, so 1 1 2 3 5 8 are the first through sixth Fibonacci numbers (not the zeroth through fifth). ''' if n <= 2: return 1 return recursiveFibonacci(n - 1) + recursiveFibonacci(n - 2) def printList(theList): ''' Prints the given list, one item per line. ''' if len(theList) > 0: print theList[0] printList(theList[1:]) def isPalindrome(s): ''' Returns true if the string s is a palindrome ''' pass if __name__ == '__main__': n = input('Number, please: ') print 'n! =', iterativeFactorial(n), '(iterative)' print 'n! =', recursiveFactorial(n), '(recursive)' print # print 'The first', n, 'Fibonacci numbers (iterative)' # for k in range(n): # print iterativeFibonacci(k + 1), # print # print # print 'The first', n, 'Fibonacci numbers (recursive)' # for k in range(n): # print recursiveFibonacci(k + 1), # print # print # # someList = ['cow', 'coatimundi', 'capybara', 'clam'] # printList(someList) # print