####### Lecture 13 ####### ####### Recursion ####### # 1. Break a problem into smaller parts # 2. Evaluate these sub-parts # 3. Put everything back together # Recursion is usually written as a function # calling itself # Recursion generally DOES NOT involved for # or while loops fibCount = 0 def fibMemo(n): return fibonacci(n, {}) # From http://www.greenteapress.com/thinkpython/thinkCSpy/html/chap04.html def fibonacci(n, memoDict): """Calculates the nth fibonacci number""" # Counting the number of calls global fibCount fibCount += 1 # Memoized solution if n in memoDict: return memoDict[n] # Base cases if n == 0 or n == 1: return 1 # Recursive case else: result = fibonacci(n-1, memoDict) + fibonacci(n-2, memoDict) # Add the result to the dictionary memoDict[n] = result return result print fibMemo(3), fibCount print fibMemo(36), fibCount - 5 # I know fibCount is 5 for fib(3) def reverseString(string): """returns string in reverse""" # Base case if string == '': return '' ## if len(string) == 1: ## return string # Recursive case else: return string[-1] + reverseString(string[:-1]) #print reverseString('hello')