Docsity

UNIT 5A Recursion: Introduction, Summaries of Physics

Partial preview of the text

Download UNIT 5A Recursion: Introduction and more Summaries Physics in PDF only on Docsity!

UNIT 5A

Recursion: Introduction

IN ORDER TO UNDERSTAND RECURSION, ONE SHOULD FIRST UNDERSTAND RECURSION.

Announcements

  • First written exam next week Wednesday
  • All material from beginning is fair game
    • There are sample exams on the resources page

This time

  • Introduction to recursion
  • What it is
  • Recursion and the stack
  • Recursion and iteration
  • Examples of simple recursive functions
  • Geometric recursion: fractals

Recursion

The Loopless Loop

Recursive Definitions

Every recursive function definition includes two parts:

  • Base case(s) (non-recursive) One or more simple cases that can be done right away
  • Recursive case(s) One or more cases that require solving “simpler” version(s) of the original problem. - By “simpler”, we mean “smaller” or “shorter” or “closer to the base case”.

Example: Factorial

  • n! = n × (n-1) × (n-2) × … × 1 2! = 2 × 1 3! = 3 × 2 × 1 4! = 4 × 3 × 2 × 1
  • alternatively: 0! = 1 (Base case) n! = n × (n-1)! (Recursive case) So 4! = 4 × 3!3! = 3 × 2!2! = 2 × 1!1! = 1 × 0!

Recursion conceptually

4! = 4(3!) 3! = 3(2!) 2! = 2(1!) 1! = 1 (0!) = 1(1) = 1 Compute the base case make smaller instances of the same problem

Recursion conceptually

4! = 4(3!) 3! = 3(2!) 2! = 2(1!) = 2 1! = 1 (0!) = 1(1) = 1 Compute the base case make smaller instances of the same problem build up the result

Recursion conceptually

4! = 4(3!) = 24 3! = 3(2!) = 6 2! = 2(1!) = 2 1! = 1 (0!) = 1(1) = 1 Compute the base case make smaller instances of the same problem build up the result

Recursive Factorial in Python

0! = 1 (Base case)

n! = n × (n-1)! (Recursive case)

def factorial(n) : if n == 0: # base case return 1 else: # recursive case return n * factorial(n-1)

Inside Python Recursion

factorial(4)? = 4 * factorial(3) S T A C K n=

Inside Python Recursion

factorial(4)? = 4 * factorial(3) S T A C K factorial(3)? n= n=

Inside Python Recursion

factorial(4)? = 4 * factorial(3) S T A C K factorial(3)? = 3 * factorial(2) factorial(2)? n= n= n=

Inside Python Recursion

factorial(4)? = 4 * factorial(3) S T A C K factorial(3)? = 3 * factorial(2) factorial(2)? = 2 * factorial(1) n= n= n=