UNIT 5A Recursion: Introduction, Summaries of Physics

A recursive function is one that calls itself. Infinite loop? Not necessarily, not if next(x) needs less work than x.

Typology: Summaries

2022/2023

Uploaded on 03/01/2023

kavinsky
kavinsky 🇺🇸

4.4

(28)

286 documents

1 / 53

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
UNIT 5A
Recursion: Introduction
1
IN ORDER TO UNDERSTAND RECURSION,
ONE SHOULD FIRST UNDERSTAND RECURSION.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35

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=