Recursion Examples.

Slides:



Advertisements
Similar presentations
Basics of Recursion Programming with Recursion
Advertisements

PYTHON FRUITFUL FUNCTIONS CHAPTER 6 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
Recursion. Recursion is a powerful technique for thinking about a process It can be used to simulate a loop, or for many other kinds of applications In.
Recursion Ellen Walker CPSC 201 Data Structures Hiram College.
Error Measurement and Iterative Methods
Kavita Math231 Recursion and Iteration. Kavita Math231 We use Recursion when we have to perform a complex task that can be broken into the several subtasks.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
Pseudocode and Algorithms
CS 106 Introduction to Computer Science I 03 / 28 / 2008 Instructor: Michael Eckmann.
Topic 7 – Recursion (A Very Quick Look). CISC 105 – Topic 7 What is Recursion? A recursive function is a function that calls itself. Recursive functions.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Comp 245 Data Structures Recursion. What is Recursion? A problem solving concept which can be used with languages that support the dynamic allocation.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Fall Week 3 CSCI-141 Scott C. Johnson.  Say we want to draw the following figure ◦ How would we go about doing this?
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
Object Oriented Programming Spring COMSATS Institute of Information Technology Functions OOP in C++ by Robert Lafore - Chapter#5 Kaleem Ullah
Principles of Programming Chapter 11: Recursive Function  In this chapter, you will learn about  Recursion function 1 NI S1 2009/10.
Advanced Computer Architecture and Parallel Processing Rabie A. Ramadan http:
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Edited by Malak Abdullah Jordan University of Science and Technology Data Structures Using C++ 2E Chapter 6 Recursion.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Recursion Review: A recursive function calls itself, but with a smaller problem – at least one of the parameters must decrease. The function uses the results.
Question : How many different ways are there to climb a staircase with n steps (for example, 100 steps) if you are allowed to skip steps, but not more.
Principles of Programming - NI Simple Recursion Recursion is where a function calls itself. Concept of recursive function: A recursive function is.
Halting Measures and Termination Arguments CS 5010 Program Design Paradigms “Bootcamp” Lesson TexPoint fonts used in EMF. Read the TexPoint manual.
COP INTERMEDIATE JAVA Recursion. The term “recursion” refers to the fact that the same computation recurs, or occurs repeatedly, as a problem is.
7. RECURSIONS Rocky K. C. Chang October 12, 2015.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
Recursion.
Recursion The programs discussed so far have been structured as functions that invoke one another in a disciplined manner For some problems it is useful.
Recursion Topic 5.
Chapter 15 Recursion.
RECURSION.
Chapter 15 Recursion.
CSE 341 Lecture 5 efficiency issues; tail recursion; print
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Ruth Anderson UW CSE 160 Winter 2017
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Applied Algorithms (Lecture 17) Recursion Fall-23
Algorithm Analysis (for Divide-and-Conquer problems)
Algorithm design and Analysis
Dynamic Programming.
Recursion UW CSE 160 Winter 2017
Recursion Spring 2015 UW CSE 160
Recursion UW CSE 160 Spring 2018
Recursion Winter 2014 UW CSE 140
Ruth Anderson UW CSE 140 Winter 2014
Coding Concepts (Basics)
Unit 3 Test: Friday.
Conditional and iterative statements
Recursion UW CSE 160 Winter 2016
Recursion Taken from notes by Dr. Neil Moore
Java Programming: Chapter 9: Recursion Second Edition
Last Class We Covered Recursion Stacks Parts of a recursive function:
Recursive Algorithms 1 Building a Ruler: drawRuler()
Recursion Review Spring 2019 CS 1110
Lecture 6 - Recursion.
Presentation transcript:

Recursion Examples

Recursion (review)

Recursion (review) Scenario: You are waiting in line for a concert. You can't see the front of the line, but you want to know your place in the line. The person at the front, knows they are at the front! Base case You ask the person in front of you: “what is your place in the line?” Recursive call When the person in front of you figures it out and tells you, add one to that answer. Use the solution to the smaller problem

Iteration vs. Recursion Iteration and recursion are somewhat related Converting iteration to recursion is formulaic, but converting recursion to iteration can be more tricky Iterative Recursive def fact_iter(n): total, k = 1, 1 while k <= n: total, k = total*k, k+1 return total def fact(n): if n == 0: return 1 else: return n * fact(n-1) Names: n, total, k, fact_iter Names: n, fact

Sum Digits Let’s implement a recursive function to sum all the digits of `n`. Assume `n` is positive. def sum_digits(n): """Calculates the sum of the digits `n`. >>> sum_digits(8) 8 >>> sum_digits(18) 9 >>> sum_digits(2018) 11 """ "*** YOUR CODE HERE ***" One or more base cases One or more recursive calls with simpler arguments. Using the recursive call to solve our larger problem.

Sum Digits 1 def sum_digits(n): 2 """Calculates the sum of the digits n 3 >>> sum_digits(8) 4 8 5 >>> sum_digits(18) 6 9 7 >>> sum_digits(2018) 8 11 9 """ 10 if n < 10: 11 return n 12 else: 13 all_but_last, last = n // 10, n % 10 14 return sum_digits(all_but_last) + last

Order of Recursive Calls see demo 1

Cascade Goal: Print out a cascading tree of a positive integer n. Demo Cascade Goal: Print out a cascading tree of a positive integer n. >>> cascade(486) Ideas: If n is a single digit, just print it out! 486 48 4 Otherwise, let cascade(n // 10) take care of the middle and print(n) around it >>> cascade(48) 1 def cascade(n): 1 def cascade(n): 2 if n < 10: 3 print(n) 1 def cascade(n): 2 if n < 10: 3 print(n) 4 else: 5 print(n) 6 cascade(n // 10) 7 print(n) 48 4 >>> cascade(4) 4

The Cascade Function Each cascade frame is from a different call to cascade. Until the Return value appears, that call has not completed. Any statement can appear before or after the recursive call. Output 123 12 1 12 Base case http://pythontutor.com/composingprograms.html#code=def%20cascade%28n%29%3A%0A%20%20%20%20if%20n%20%3C%2010%3A%0A%20%20%20%20%20%20%20%20print%28n%29%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20print%28n%29%0A%20%20%20%20%20%20%20%20cascade%28n//10%29%0A%20%20%20%20%20%20%20%20print%28n%29%0A%0Acascade%28123%29&cumulative=true&curInstr=0&mode=display&origin=composingprograms.js&py=3&rawInputLstJSON=%5B%5D

Two Implementations of Cascade Demo Two Implementations of Cascade 1 def cascade(n): 2 if n < 10: 3 print(n) 4 else: 5 print(n) 6 cascade(n // 10) 7 print(n) 1 def cascade(n): 2 print(n) 3 if n >= 10: 4 cascade(n // 10) 5 print(n) If two implementations are equally clear, then shorter is usually better In this case, the longer implementation might be more clear When learning to write recursive functions, put the base case/s first

Fibonacci

Fibonacci Sequence + + + + + + + n 1 2 3 4 5 6 7 8 ... 30 fib(n) 13 21 1 2 3 4 5 6 7 8 ... 30 fib(n) 13 21 832040 + + + + + + +

fib(1) == 1 fib(2) == 1 fib(3) == 2 fib(4) == 3 fib(5) == 5 Fibonacci's rabbits

Fibonacci Goal: Return the nth Fibonacci number. Ideas: Demo Fibonacci Goal: Return the nth Fibonacci number. n 1 2 3 4 5 6 7 8 ... 30 fib(n) 13 21 832040 Ideas: The first two Fibonacci numbers are known; if we ask for the 0th or 1st Fibonacci number, we know it immediately Otherwise, we sum up the previous two Fibonacci numbers Think to place in line problem. 1 def fib(n): 2 if n == 0: 3 return 0 4 elif n == 1: 5 return 1 1 def fib(n): 1 def fib(n): 2 if n == 0: 3 return 0 4 elif n == 1: 5 return 1 6 else: 7 return fib(n - 2) + fib(n - 1)

Fibonacci Call Tree fib(5) fib(3) fib(4) fib(1) fib(2) fib(0) 1 fib(2) fib(2) fib(1) fib(0) 1 fib(3) fib(n): a tree-recursive process

Broken Fibonacci Wrong value Error >>> broken_fib(5) 1 def fib(n): 2 if n == 0: 3 return 0 4 elif n == 1: 5 return 1 6 else: 7 return fib(n - 1) + fib(n - 2) 1 def broken_fib(n): 2 if n == 0: 3 return 0 4 # Missing base case! 5 else: 6 return broken_fib(n - 2) + ……………………………….. broken_fib(n - 1) broken_fib(5) broken_fib(3) >>> broken_fib(5) broken_fib(1) Traceback (most recent call last): ... RecursionError: maximum recursion depth exceeded in comparison broken_fib(-1)

fib(5) fib(3) fib(1) fib(-1) Never computed! fib(-3) Broken fib(n)

Counting Partitions

Count Partitions Goal: Count the number of ways to give out n ( > 0) pieces of chocolate if nobody can have more than m (> 0) pieces. "How many different ways can I give out 6 pieces of chocolate if nobody can have more than 4 pieces?" >>> count_part(6, 4) 9 2 + 4 = 6 1 + 1 + 4 = 6 Largest Piece: 4 2 + 2 + 2 = 6 1 + 1 + 2 + 2 = 6 1 + 1 + 1 + 1 + 2 = 6 Largest Piece: 2 3 + 3 = 6 1 + 2 + 3 = 6 1 + 1 + 1 + 3 = 6 Largest Piece: 3 1 + 1 + 1 + 1 + 1 + 1 = 6 Largest Piece: 1

Count Partitions 2 + 4 1 + 1 + 4 3 + 3 1 + 2 + 3 1 + 1 + 1 + 3 2 + 2 + 2 1 + 1 + 2 + 2 1 + 1 + 1 + 1 + 2 1 + 1 + 1 + 1 + 1 + 1

Count Partitions Ideas: Find simpler instances of the problem Explore two possibilities: Use a 4 Don’t use a 4 Solve two simpler problems: count_part(2, 4) count_part(6, 3) Sum up the results of these smaller problems!

Count Partitions Ideas: Find simpler instances of the problem Explore two possibilities: Use a 4 Don’t use a 4 1 def count_part(n, m): 2 if 3 else: 4 with_m = count_part(n-m, m) 5 wo_m = count_part(n, m - 1) 6 return with_m + wo_m Solve two simpler problems: count_part(2, 4) count_part(6, 3) Sum up the results of these smaller problems!

Count Partitions How do we know we’re done? (6, 4) Use a 4 Don’t use a 4 4 + 4 + ... ≠ 6 4 + 2 = 6 (2, 4) (6, 3) If n is negative, then we cannot get to a valid partition (-2, 4) (2, 3) Use a 4 Don’t use a 4 ... If n is 0, then we have arrived at a valid partition Use a 3 Don’t use a 3 (-1, 3) (2, 2) (0, 2) (2, 1) Use a 2 Don’t use a 2 If the largest piece we can use is 0, then we cannot get to a valid partition 1 (1, 1) (2,0) (1, 0) (0, 1) 1

Count Partitions Ideas: Explore two possibilities: Use a 4 Demo Count Partitions Ideas: Explore two possibilities: Use a 4 Don’t use a 4 1 def count_part(n, m): 2 if n == 0: 3 return 1 4 elif n < 0: 5 return 0 6 elif m == 0: 7 return 0 8 else: 9 with_m = count_part(n-m, m) 10 wo_m = count_part(n, m - 1) 11 return with_m + wo_m 1 def count_part(n, m): if n == 0: return 1 elif n < 0: return 0 elif m == 0: else: 9 with_m = count_part(n-m, m) 10 wo_m = count_part(n, m - 1) 11 return with_m + wo_mo_m 1 def count_part(n, m): 2 if n == 0: 3 return 1 4 elif n < 0: 5 return 0 elif m == 0: return 0 8 else: 9 with_m = count_part(n-m, m) 10 wo_m = count_part(n, m - 1) 11 return with_m + wo_m 1 def count_part(n, m): if n == 0: return 1 elif n < 0: return 0 elif m == 0: else: with_m = count_part(n - m, m) wo_m = count_part(n, m - 1) return with_m + wo_m Solve two simpler problems: count_part(2, 4) count_part(6, 3) Sum up the results of these smaller problems! http://pythontutor.com/composingprograms.html#code=def%20count_part%28n,%20m%29%3A%0A%20%20%20%20if%20n%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20return%201%0A%20%20%20%20elif%20n%20%3C%200%3A%0A%20%20%20%20%20%20%20%20return%200%0A%20%20%20%20elif%20m%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20return%200%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20with_m%20%3D%20count_part%28n%20-%20m,%20m%29%0A%20%20%20%20%20%20%20%20wo_m%20%3D%20count_part%28n,%20m%20-%201%29%0A%20%20%20%20%20%20%20%20return%20with_m%20%2B%20wo_m%0A%0Aresult%20%3D%20count_partitions%285,%203%29%0A%0A%23%201%20%2B%201%20%2B%201%20%2B%201%20%2B%201%20%3D%205%0A%23%201%20%2B%201%20%2B%201%20%2B%202%20%20%20%20%20%3D%205%0A%23%201%20%2B%202%20%2B%202%20%20%20%20%20%20%20%20%20%3D%205%0A%23%201%20%2B%201%20%2B%203%20%20%20%20%20%20%20%20%20%3D%205%0A%23%202%20%2B%203%20%20%20%20%20%20%20%20%20%20%20%20%20%3D%205%0A&cumulative=true&curInstr=0&mode=display&origin=composingprograms.js&py=3&rawInputLstJSON=%5B%5D How do we know we’re done? If n is 0, then we have arrived at a valid partition If n is negative, then we cannot get to a valid partition If the largest piece we can use is 0, then we cannot get to a valid partition

Takeaways Tree recursion allows you to explore different possibilities Oftentimes, the recursive calls for tree recursion represent different choices One such choice is “do I use this value, or do I try another?” Sometimes it is easier to start with the recursive cases, and see which base cases those lead you to

If Time - Speeding Up Recursion (Teaser for the ~Future~)

Back to Fib fib(5) fib(3) fib(4) fib(1) fib(2) fib(0) 1 fib(2) fib(1) Demo Back to Fib fib(5) fib(3) fib(4) fib(1) fib(2) fib(0) 1 fib(2) fib(1) fib(0) 1 fib(3)

Basic Idea to Improve: 1 def better_fib(n): 2 if n == 0: 3 return 0 4 elif n == 1: 5 return 1 6 elif already called better_fib(n): 7 return stored value 8 else: 9 store & return better_fib(n - 2) + better_fib(n - 1)

Summary Recursion has three main components Base case/s: The simplest form of the problem Recursive call/s: Smaller version of the problem Use the solution to the smaller version of the problem to arrive at the solution to the original problem When working with recursion, use functional abstraction: assume the recursive call gives the correct result Tree recursion makes multiple recursive calls and explores different choices Use doctests and your own examples to help you figure out the simplest forms and how to make the problem smaller