11/12/14 ¡ CSCI-1101A Recursion Mohammad T . Irfan Roadmap Before After Thanksgiving Thanksgiving • Recursion • Graph algorithms • Object-oriented • Google’s web search programming algorithm • Lab: relevant topics + • Lab: Continue final start final project of project, building 2048 game website 1 ¡
11/12/14 ¡ Real world example of recursion u Google Maps Another real-world example 2 ¡
11/12/14 ¡ Inception—Hollywood’s version of recursion u Can we write a program to describe what they were doing? Code 3 ¡
11/12/14 ¡ 2 ways of understanding recursion 1. Tracing diagram: Cook a small example and simulate the recursive function calls 2. Black box: Imagine the recursive function is a magical black box 3 elements of recursion 1. Base case—the case where you don’t need recursion to give an answer 2. Recursive case (forward flow)—the function calls itself with a different argument 3. Kick (backward flow)—return the result 4 ¡
11/12/14 ¡ Problem: compute factorial u Factorial of a number u factorial(4) = 4 * 3 * 2 * 1 u 4! = 4 * 3! u if n == 0: # Base case u n! = 1 u If n >= 1 # Recursive case u n! = n * (n-1)! Code 5 ¡
11/12/14 ¡ Exercise 15.2 u Problem: Find the n-th number in the Fibonacci sequence u Fibonacci Sequence u 0, 1, 1, 2, 3, 5, 8, 13, 21, ... u f 0 = 0 u f 1 = 1 u f n = f n-1 + f n-2 if n > 1 u What is the base case? u What is the recursive case? Code 6 ¡
11/12/14 ¡ Fibonacci numbers in nature From: http://britton.disted.camosun.bc.ca/fibslide/jbfibslide.htm Other examples (Wikipedia) Yellow Chamomile head showing the arrangement in 21 (blue) and 13 (aqua) spirals. 7 ¡
11/12/14 ¡ When there’s no formula... u Main challenge u Devise a recurrence relation first Problem: Test for palindrome u Recurrence relation? u Do an example u Try to break the whole task into smaller tasks u A string is a palindrome if u its first and last letters match u the substring in between the first and last letters is a palindrome 8 ¡
11/12/14 ¡ Code Problem: find the max of a list u Recurrence relation u Work out an example u The max of a list is the larger of two numbers: The list’s first element and 1. The max of the rest of the list (model the rest of 2. the list as a smaller list) 9 ¡
11/12/14 ¡ Code Problem: find the sum of a list u What is the recurrence relation? u Sum of a list is the sum of two numbers The first number of the list 1. The sum of the rest of the list (consider that as a 2. smaller list) 10 ¡
11/12/14 ¡ Video Lectures u Counting the number of vowels in a string (5 min) u http://bit.ly/1qEIhsX u Series sum (4 min) u http://bit.ly/10Yz4Fc u Binary Search (15 min) [Lab] u http://bit.ly/1xj43dg Exam 5 (December 9) u Topics from recursion u Recursion – Chapter 15.4 u Exercises 15.9—15.13: Draw the tracing diagrams for very small examples to find what these functions are doing u Binary search (lab) u Video lectures u Optional: Guttag’s Section 4.3 11 ¡
Recommend
More recommend