20
Recursion CS 112 @ GMU

Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

  • Upload
    others

  • View
    26

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Recursion

CS 112 @ GMU

Page 2: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

2

Recursion

Page 3: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Recursion

• recursion: something defined in terms of itself. • function recursion: when a function calls itself.

Sometimes this happens directly, sometimes indirectly.→ direct: function call to itself is right there, in the function body.→ indirect: example: foo calls bar, bar calls foo.

Page 4: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Recursion

• recursion: something defined in terms of itself. • function call recursion: when a function calls

itself.

Example of Recursion: evenness

def is_even(n):if n==0:

return Trueelif n==1:

return Falseelse:

equivalent = is_even (n-2)return equivalent

Page 5: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Indirect Recursion

Indirect Recursion: evenness and oddness

def even(n):if n==0:

return Truereturn odd(n-1)

def odd(n):if n==0:

return Falsereturn even(n-1)

• indirect recursion: a function call indirectly causes itself to be called again.

Page 6: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Recursion Basics• Think of your task in terms of "base cases" and "recursive cases".

• base case: inputs where the answer is directly calculated with no recursive call; the parameters' values are sufficient information to find the answer.→ even(0) is known to be True.

• recursive case: inputs where the answer is calculated by recursively calling the function again on a "smaller" problem.→ "smaller" means we made progress towards a base case.→ example: even(5) calculates even(3). We've made progress towards calling to even(1), a base case.

Page 7: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Recursion RecipeTo use recursion, you might want to follow this pattern:

Task Thoughts1. Identify the base cases can be calculated without need for

recursive call.2. Identify the recursive cases: can define solution in terms of other function calls

Is the recursive step using the method on a "smaller" problem? (needs to be yes!)

3. reach code for the base cases first

(allows us to 'escape' before committing to the recursive calls)

4. Write code for the recursive cases after the bases cases

(only use recursion when base cases aren't sufficient yet)

→ handle any error conditions like base cases.Example: factorial shouldn't be called on negative numbers; choose how to exit (or what to return) meaningfully. No recursive call needed/wanted.

Page 8: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Example: Factorial

factorialdef fact(n):

if n<=1:return 1

else:return n * fact(n-1)

Mathematical definition:fact(n)= 1 , if n<=1 # base case

n*(fact(n-1)) , if n>1 # recursive case

draw out memory (in the visualizer) for fact(5).

Page 9: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Separate Calls

99

Each recursive call is distinct:• separate frame on the execution stack• separate local variables

→ it's as if they are separate functions with the same implementation inside.

Page 10: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Factorial: Running It

Suppose we call fact(3).

fact(3) uses recursion, calls fact(2) (and is paused)fact(2) uses recursion, calls fact(1) (and is paused)

fact(1) uses base case, directly returns value 1.fact(2) unpauses, receives the 1, returns 2*1 == 2.

fact(3) unpauses, receives the 2, returns 3*2 == 6.

Page 11: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Calculation via recursion

fib(n) = 1, if n=0 or n=1= fib(n-1)+fib(n-2), otherwise

n fib(n)

0 11 12 1+1 = 23 1+2 = 34 2+3 = 55 3+5 = 86 5+8 = 13… …

fibonaccidef fib (n):

if n<=1:return 1

return fib(n-1)+fib(n-2)

draw out memory/visualize for fib(4).

Page 12: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Practice Problems

Thought experiments: How can you use recursion to…

→ find the log of a number? (return an int)→ solve a maze?→ solve a sudoku?

Page 13: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

• Write a function, gcd(a,b), that calculates the greatest common denominator of a and b. → write it with a loop first (iteratively)→ then try again with recursion.

Euclid's Algorithm: Assume a>=b. Repeatedly calculate (a,b)=(b,a%b) until b==0. a's last value is the gcd of the original a and b values.

gcd(150,60):150%60 == 3060%30 == 0

→ gcd(150,60)==30

gcd(78,18):78%18 == 618% 6 == 0

→ gcd(78,18)==6

gcd(2730,858):2730 % 858 == 156858 % 156 == 78156 % 78 == 0→ gcd(2730,858) == 78

Practice Problem

Sample calculations:

Page 14: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

• Write a function, sum_list(xs), which sums all the integers in the list. The catch is that there is an arbitrary number of dimensions at each spot in the list! (something like [1,[2],[3,[4]],[[[5]]] ] could be supplied). → use the type() function and recursion to solve this.→ even better: use isinstance(val,ty).

Examples: isinstance( 5, int ) → Trueisinstance( [2,3,4], list) → Trueisinstance( 5, list) → False

Practice Problem

Page 15: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

when should I use recursion?Recursion is sometimes much slower than an iterative solution (but not always).Pros:→ each call has its own local scope/local variables→ might look quite like the mathematical def'n→ easy to handle irregular shapes (as did sum_list)

Cons:→ uses more stack space (limits recursion depth!)→ performing function call takes a bit more time than starting next loop iteration

Page 16: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

Use recursion if the solution is straightforward and easy to verify

your calculation is correct.→ If it runs 'fast enough', congrats! You're done.→ If you test realistically largest inputs and the stack doesn't overflow, congrats! You'll get away with using recursion.

when should I use recursion?

Page 17: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

If the number of recursive calls isn't expected to be excessively high, it could be a good approach.

→ Given a list of n elements: either need <n recursive calls, or n known to be small always.→ fact(n) had n recursive calls. Only acceptable on smallish values of n (n>990 or so crashes my machine)→ fib(n) had far more than n recursive calls! Horrible time to use recursion.→ gcd(a,b) had far less than a or b calls – if this solution is easier for you to write, it's an okay time to use recursion.→ sum_list(xs) had as many recursive calls as the number of sub-lists. Given the difficulty of writing an imperative solution, this is a good tradeoff.

when should I use recursion?

Page 18: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

When is recursion truly useful?

• Once we start defining our own datatypes (classes), we may have recursively defined structure

• Writing non-recursive code over these values is quite difficult!– Rarely enough recursive structure to overflow stack– Recursion is a natural/good choice here

• We're not quite there yet in CS 112! This is round one of learning recursion. – To be continued in later classes…

Page 19: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

19

Recursion

Page 20: Recursion - George Mason Universitymarks/112/slides/8.recursion.pdf · Recursion •recursion: something defined in terms of itself. •function recursion: when a function calls itself

POLL – 8A

• recursion