SlideShare a Scribd company logo
1 of 9
Download to read offline
Chapter 7
Recursion
Recursive definitions
and recursive functions
When we define something in terms that relates back to what we define
itself, then we have what is called a recursive definition. 

Recursion: See Recursion.
Not all examples are meaningless like this. Those that are useful consists of
base cases and recursive cases.
Base cases
Recursive case
Base case
Recursive case
The factorial of a number n, or the Fibonacci numbers, are classically
defined recursively like this. In the base cases we know the value of the
function immediately, and in the recursive cases we have to do some
computations that involves the function on another input. That “another
input” has to get us closer to a base case, or we will never get an answer—
similar to how we will never terminate an infinite loop.

Determining if a recursive function has a value is as hard as determining if
an algorithm terminates, so we cannot check this; we need to guarantee it
ourselves.
Base cases
Recursive case
Base case
Recursive case
If we have a recursive definition, then translating that into a Python function
that calculates a value based on it is usually straightforward. Recursive
functions work just as you would expect from recursive definitions, and we
won’t talk more about how to write recursive functions in this lecture. We
will, instead, see how function calls are generally implemented on
computers and how this makes recursive functions possible.
When we call a recursive function, we start a chain of function calls that
(hopefully) eventually hit a base cases where we can get a value. Then,
returning from the recursion, we can combine the result of function calls
with values in each instance of function calls. We return from the function
calls in the reverse order as we made them.
Function calls, call
stacks, and call stack
frames
If you have, so far, considered Python functions not much different from
mathematical functions—just mappings from input to output—except that
they can have side-effects, then this is because it is a useful abstraction. It
is a useful way to think about functions and you rarely need to think deeper
about them. You will learn something about computers if you try to
understand how functions and function calls are implemented on a machine.
When you run a computer program, you essentially have a sequence of
simple instructions and the CPU can execute them and, when the
instructions say so, jump to another point in the instructions. When you call
a function, you need to provide it with arguments and reserve space for its
local variables. If you want to return from the function again, and the
function can be called from more than one location, you need to remember
that as well.

Caveat: Python runs on a virtual machine, so actually is a little different than
explained here, but the concepts are the same.
If we have a recursive function, we will have to have several instances of
calls to the same function, so we cannot just reserve space for the local
variables and return location ones. We have to dynamically do this as
needed. (This isn’t just the case for recursive functions but any function that
might, through some chain of function calls, be called again before its first
call returns).
The way computers solve this issue is to have a stack of function calls, or
function frames they are sometimes called. When you call a function, you
push a return location, space for local variables, and function arguments on
the top of the stack. When you then execute the code for the function, you
access local variables relative to the stack pointer. If the same function is
called more than once, the active one is the one at the top of the stack.
When you return from a function call, you remove the call frame from the top
of the stack and continue executing from the location you stored in the
frame.
Tail-recursion
A special class of recursive functions are called tail-recursive. Those are
functions where the recursive call is the very last thing the function does. It
doesn’t do anything with the result of the recursive call except return it.
In a chain of tail-recursive calls, all except the first function call will have the
same return location. Since we do not modify any local variables after the
recursive calls, variables in the frames on the stack will not be modified ever
again before they are popped off the stack.
In such situations it is possible to optimize away the actual recursion by
reusing the call frame of the first function. In many programming languages,
this optimization is implemented. Python isn’t as dependent on functions
and recursion as other languages, and the optimization is not implemented
her. We can always implement it ourselves, though.
It sometimes requires a little rewriting to make a function tail-recursive. If
there is no more than one recursive call per function, it is relatively easy to
do this. If not, it can still be done but it is substantially harder—and not
worth the effort in Python.

Sometimes it is easier to write a recursive function than an iterative function;
if you do this, it is good to know that you can optimize it as well.
Often the recursive function is simpler to understand than the iterative one,
but if the transformation is the same, then you start to recognize the pattern.
If you can write an iterative function straight away, then don’t bother with
going through recursion, but often it is easier to think up a recursion first and
then do the transformation. The divide and conquer algorithms do this. On
this slide, I have written a recursive selection sort and the transformation of
it. You can compare it with the iterative selection sort from chapter 5.
A very simple divide-and-conquer algorithm is quick sort. It is defined
recursively like here, and you will agree that it is a very simple function. (The
partition function is a bit more involved but you get to implement it yourself).
We cannot get rid of both recursive calls in the tail-recursion transformation,
but we can get rid of one of them. If we want to keep the stack depth small
—it is a limited resource—we can guarantee that it only grows logarithmic in
the input by only recursing on the smaller sub-problem (can you see why the
runtime is logarithmic then?)

Exercises!
Time to put recursion-fu
into practice

More Related Content

What's hot

The Function Pointer Tutorials
The Function Pointer TutorialsThe Function Pointer Tutorials
The Function Pointer TutorialsNont Banditwong
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#Riccardo Terrell
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript FundamentalsSrdjan Strbanovic
 
(3) c sharp introduction_basics_part_ii
(3) c sharp introduction_basics_part_ii(3) c sharp introduction_basics_part_ii
(3) c sharp introduction_basics_part_iiNico Ludwig
 
Decision making and loop in C#
Decision making and loop in C#Decision making and loop in C#
Decision making and loop in C#Prasanna Kumar SM
 
What's new in c# 6.0
What's new in c# 6.0What's new in c# 6.0
What's new in c# 6.0LearningTech
 
polymorphism and virtual function
polymorphism and virtual functionpolymorphism and virtual function
polymorphism and virtual functionBhanuprataparya
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8Talha Ocakçı
 
Virtual function and abstract class
Virtual function and abstract classVirtual function and abstract class
Virtual function and abstract classShweta Shah
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into JavascriptMassimo Franciosa
 
c.p function
c.p functionc.p function
c.p functiongiri5624
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2Todor Kolev
 
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? reactima
 
Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 

What's hot (20)

The Function Pointer Tutorials
The Function Pointer TutorialsThe Function Pointer Tutorials
The Function Pointer Tutorials
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
 
Php, mysq lpart3
Php, mysq lpart3Php, mysq lpart3
Php, mysq lpart3
 
Python master class 2
Python master class 2Python master class 2
Python master class 2
 
Python master class part 1
Python master class part 1Python master class part 1
Python master class part 1
 
Functional JavaScript Fundamentals
Functional JavaScript FundamentalsFunctional JavaScript Fundamentals
Functional JavaScript Fundamentals
 
(3) c sharp introduction_basics_part_ii
(3) c sharp introduction_basics_part_ii(3) c sharp introduction_basics_part_ii
(3) c sharp introduction_basics_part_ii
 
Functions
FunctionsFunctions
Functions
 
Decision making and loop in C#
Decision making and loop in C#Decision making and loop in C#
Decision making and loop in C#
 
What's new in c# 6.0
What's new in c# 6.0What's new in c# 6.0
What's new in c# 6.0
 
Function Parameters
Function ParametersFunction Parameters
Function Parameters
 
polymorphism and virtual function
polymorphism and virtual functionpolymorphism and virtual function
polymorphism and virtual function
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Virtual function and abstract class
Virtual function and abstract classVirtual function and abstract class
Virtual function and abstract class
 
Journey of a C# developer into Javascript
Journey of a C# developer into JavascriptJourney of a C# developer into Javascript
Journey of a C# developer into Javascript
 
c.p function
c.p functionc.p function
c.p function
 
Java findamentals2
Java findamentals2Java findamentals2
Java findamentals2
 
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD? WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
WHY JAVASCRIPT FUNCTIONAL PROGRAMMING IS SO HARD?
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 

Similar to Recursive Definitions and Functions

Chapter 3 introduction to algorithms handouts (with notes)
Chapter 3 introduction to algorithms handouts (with notes)Chapter 3 introduction to algorithms handouts (with notes)
Chapter 3 introduction to algorithms handouts (with notes)mailund
 
Recursion and looping
Recursion and loopingRecursion and looping
Recursion and loopingxcoolanurag
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structurecogaxor346
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptxManas40552
 
Lecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxLecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxAbuHuraira729502
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptxJuanPicasso7
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms NotesAndres Mendez-Vazquez
 
C++ Tail Recursion Using 64-bit variables
C++ Tail Recursion Using 64-bit variablesC++ Tail Recursion Using 64-bit variables
C++ Tail Recursion Using 64-bit variablesPVS-Studio
 
Intro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionIntro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionBlue Elephant Consulting
 
EuroAD 2021: ChainRules.jl
EuroAD 2021: ChainRules.jl EuroAD 2021: ChainRules.jl
EuroAD 2021: ChainRules.jl Lyndon White
 
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSINTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSKalaivaniD12
 
Recursion in C++
Recursion in C++Recursion in C++
Recursion in C++Maliha Mehr
 

Similar to Recursive Definitions and Functions (20)

Python-Functions.pptx
Python-Functions.pptxPython-Functions.pptx
Python-Functions.pptx
 
Python recursion
Python recursionPython recursion
Python recursion
 
Chapter 3 introduction to algorithms handouts (with notes)
Chapter 3 introduction to algorithms handouts (with notes)Chapter 3 introduction to algorithms handouts (with notes)
Chapter 3 introduction to algorithms handouts (with notes)
 
Recursion and looping
Recursion and loopingRecursion and looping
Recursion and looping
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Recursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & StructureRecursion vs. Iteration: Code Efficiency & Structure
Recursion vs. Iteration: Code Efficiency & Structure
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
 
Lecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptxLecture_7_StackAndRecursion (1).pptx
Lecture_7_StackAndRecursion (1).pptx
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
 
Java script function
Java script functionJava script function
Java script function
 
powerpoint 2-7.pptx
powerpoint 2-7.pptxpowerpoint 2-7.pptx
powerpoint 2-7.pptx
 
01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes01 Notes Introduction Analysis of Algorithms Notes
01 Notes Introduction Analysis of Algorithms Notes
 
S.k
S.kS.k
S.k
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
C++ Tail Recursion Using 64-bit variables
C++ Tail Recursion Using 64-bit variablesC++ Tail Recursion Using 64-bit variables
C++ Tail Recursion Using 64-bit variables
 
Intro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionIntro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, Recursion
 
EuroAD 2021: ChainRules.jl
EuroAD 2021: ChainRules.jl EuroAD 2021: ChainRules.jl
EuroAD 2021: ChainRules.jl
 
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSINTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
 
Recursion in C++
Recursion in C++Recursion in C++
Recursion in C++
 
Monad Fact #6
Monad Fact #6Monad Fact #6
Monad Fact #6
 

More from mailund

Chapter 9 divide and conquer handouts with notes
Chapter 9   divide and conquer handouts with notesChapter 9   divide and conquer handouts with notes
Chapter 9 divide and conquer handouts with notesmailund
 
Chapter 9 divide and conquer handouts
Chapter 9   divide and conquer handoutsChapter 9   divide and conquer handouts
Chapter 9 divide and conquer handoutsmailund
 
Chapter 9 divide and conquer
Chapter 9   divide and conquerChapter 9   divide and conquer
Chapter 9 divide and conquermailund
 
Chapter 7 recursion handouts
Chapter 7   recursion handoutsChapter 7   recursion handouts
Chapter 7 recursion handoutsmailund
 
Chapter 7 recursion
Chapter 7   recursionChapter 7   recursion
Chapter 7 recursionmailund
 
Chapter 5 searching and sorting handouts with notes
Chapter 5   searching and sorting handouts with notesChapter 5   searching and sorting handouts with notes
Chapter 5 searching and sorting handouts with notesmailund
 
Chapter 5 searching and sorting handouts
Chapter 5   searching and sorting handoutsChapter 5   searching and sorting handouts
Chapter 5 searching and sorting handoutsmailund
 
Chapter 5 searching and sorting
Chapter 5   searching and sortingChapter 5   searching and sorting
Chapter 5 searching and sortingmailund
 
Chapter 4 algorithmic efficiency handouts (with notes)
Chapter 4   algorithmic efficiency handouts (with notes)Chapter 4   algorithmic efficiency handouts (with notes)
Chapter 4 algorithmic efficiency handouts (with notes)mailund
 
Chapter 4 algorithmic efficiency handouts
Chapter 4   algorithmic efficiency handoutsChapter 4   algorithmic efficiency handouts
Chapter 4 algorithmic efficiency handoutsmailund
 
Chapter 4 algorithmic efficiency
Chapter 4   algorithmic efficiencyChapter 4   algorithmic efficiency
Chapter 4 algorithmic efficiencymailund
 
Chapter 3 introduction to algorithms slides
Chapter 3 introduction to algorithms slidesChapter 3 introduction to algorithms slides
Chapter 3 introduction to algorithms slidesmailund
 
Chapter 3 introduction to algorithms handouts
Chapter 3 introduction to algorithms handoutsChapter 3 introduction to algorithms handouts
Chapter 3 introduction to algorithms handoutsmailund
 
Ku 05 08 2009
Ku 05 08 2009Ku 05 08 2009
Ku 05 08 2009mailund
 
Association mapping using local genealogies
Association mapping using local genealogiesAssociation mapping using local genealogies
Association mapping using local genealogiesmailund
 
Neural Networks
Neural NetworksNeural Networks
Neural Networksmailund
 
Probability And Stats Intro
Probability And Stats IntroProbability And Stats Intro
Probability And Stats Intromailund
 
Probability And Stats Intro2
Probability And Stats Intro2Probability And Stats Intro2
Probability And Stats Intro2mailund
 
Linear Regression Ex
Linear Regression ExLinear Regression Ex
Linear Regression Exmailund
 
Course Introduction
Course IntroductionCourse Introduction
Course Introductionmailund
 

More from mailund (20)

Chapter 9 divide and conquer handouts with notes
Chapter 9   divide and conquer handouts with notesChapter 9   divide and conquer handouts with notes
Chapter 9 divide and conquer handouts with notes
 
Chapter 9 divide and conquer handouts
Chapter 9   divide and conquer handoutsChapter 9   divide and conquer handouts
Chapter 9 divide and conquer handouts
 
Chapter 9 divide and conquer
Chapter 9   divide and conquerChapter 9   divide and conquer
Chapter 9 divide and conquer
 
Chapter 7 recursion handouts
Chapter 7   recursion handoutsChapter 7   recursion handouts
Chapter 7 recursion handouts
 
Chapter 7 recursion
Chapter 7   recursionChapter 7   recursion
Chapter 7 recursion
 
Chapter 5 searching and sorting handouts with notes
Chapter 5   searching and sorting handouts with notesChapter 5   searching and sorting handouts with notes
Chapter 5 searching and sorting handouts with notes
 
Chapter 5 searching and sorting handouts
Chapter 5   searching and sorting handoutsChapter 5   searching and sorting handouts
Chapter 5 searching and sorting handouts
 
Chapter 5 searching and sorting
Chapter 5   searching and sortingChapter 5   searching and sorting
Chapter 5 searching and sorting
 
Chapter 4 algorithmic efficiency handouts (with notes)
Chapter 4   algorithmic efficiency handouts (with notes)Chapter 4   algorithmic efficiency handouts (with notes)
Chapter 4 algorithmic efficiency handouts (with notes)
 
Chapter 4 algorithmic efficiency handouts
Chapter 4   algorithmic efficiency handoutsChapter 4   algorithmic efficiency handouts
Chapter 4 algorithmic efficiency handouts
 
Chapter 4 algorithmic efficiency
Chapter 4   algorithmic efficiencyChapter 4   algorithmic efficiency
Chapter 4 algorithmic efficiency
 
Chapter 3 introduction to algorithms slides
Chapter 3 introduction to algorithms slidesChapter 3 introduction to algorithms slides
Chapter 3 introduction to algorithms slides
 
Chapter 3 introduction to algorithms handouts
Chapter 3 introduction to algorithms handoutsChapter 3 introduction to algorithms handouts
Chapter 3 introduction to algorithms handouts
 
Ku 05 08 2009
Ku 05 08 2009Ku 05 08 2009
Ku 05 08 2009
 
Association mapping using local genealogies
Association mapping using local genealogiesAssociation mapping using local genealogies
Association mapping using local genealogies
 
Neural Networks
Neural NetworksNeural Networks
Neural Networks
 
Probability And Stats Intro
Probability And Stats IntroProbability And Stats Intro
Probability And Stats Intro
 
Probability And Stats Intro2
Probability And Stats Intro2Probability And Stats Intro2
Probability And Stats Intro2
 
Linear Regression Ex
Linear Regression ExLinear Regression Ex
Linear Regression Ex
 
Course Introduction
Course IntroductionCourse Introduction
Course Introduction
 

Recently uploaded

Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Patrick Diehl
 
Speech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxSpeech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxpriyankatabhane
 
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)riyaescorts54
 
Davis plaque method.pptx recombinant DNA technology
Davis plaque method.pptx recombinant DNA technologyDavis plaque method.pptx recombinant DNA technology
Davis plaque method.pptx recombinant DNA technologycaarthichand2003
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxNandakishor Bhaurao Deshmukh
 
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdf
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdfBUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdf
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdfWildaNurAmalia2
 
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Nistarini College, Purulia (W.B) India
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfSELF-EXPLANATORY
 
Scheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxScheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxyaramohamed343013
 
Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024AyushiRastogi48
 
OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024innovationoecd
 
FREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naFREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naJASISJULIANOELYNV
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPirithiRaju
 
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdfPests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdfPirithiRaju
 
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxGenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxBerniceCayabyab1
 
User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)Columbia Weather Systems
 
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPirithiRaju
 
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingBase editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingNetHelix
 
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptx
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptxSulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptx
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptxnoordubaliya2003
 

Recently uploaded (20)

Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?Is RISC-V ready for HPC workload? Maybe?
Is RISC-V ready for HPC workload? Maybe?
 
Speech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxSpeech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptx
 
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
(9818099198) Call Girls In Noida Sector 14 (NOIDA ESCORTS)
 
Davis plaque method.pptx recombinant DNA technology
Davis plaque method.pptx recombinant DNA technologyDavis plaque method.pptx recombinant DNA technology
Davis plaque method.pptx recombinant DNA technology
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
 
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdf
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdfBUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdf
BUMI DAN ANTARIKSA PROJEK IPAS SMK KELAS X.pdf
 
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
 
Scheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docxScheme-of-Work-Science-Stage-4 cambridge science.docx
Scheme-of-Work-Science-Stage-4 cambridge science.docx
 
Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024Vision and reflection on Mining Software Repositories research in 2024
Vision and reflection on Mining Software Repositories research in 2024
 
OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024OECD bibliometric indicators: Selected highlights, April 2024
OECD bibliometric indicators: Selected highlights, April 2024
 
FREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by naFREE NURSING BUNDLE FOR NURSES.PDF by na
FREE NURSING BUNDLE FOR NURSES.PDF by na
 
Pests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdfPests of castor_Binomics_Identification_Dr.UPR.pdf
Pests of castor_Binomics_Identification_Dr.UPR.pdf
 
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdfPests of Blackgram, greengram, cowpea_Dr.UPR.pdf
Pests of Blackgram, greengram, cowpea_Dr.UPR.pdf
 
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptxGenBio2 - Lesson 1 - Introduction to Genetics.pptx
GenBio2 - Lesson 1 - Introduction to Genetics.pptx
 
User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)User Guide: Orion™ Weather Station (Columbia Weather Systems)
User Guide: Orion™ Weather Station (Columbia Weather Systems)
 
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdfPests of jatropha_Bionomics_identification_Dr.UPR.pdf
Pests of jatropha_Bionomics_identification_Dr.UPR.pdf
 
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editingBase editing, prime editing, Cas13 & RNA editing and organelle base editing
Base editing, prime editing, Cas13 & RNA editing and organelle base editing
 
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptx
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptxSulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptx
Sulphur & Phosphrus Cycle PowerPoint Presentation (2) [Autosaved]-3-1.pptx
 

Recursive Definitions and Functions

  • 1. Chapter 7 Recursion Recursive definitions and recursive functions When we define something in terms that relates back to what we define itself, then we have what is called a recursive definition. Recursion: See Recursion. Not all examples are meaningless like this. Those that are useful consists of base cases and recursive cases.
  • 2. Base cases Recursive case Base case Recursive case The factorial of a number n, or the Fibonacci numbers, are classically defined recursively like this. In the base cases we know the value of the function immediately, and in the recursive cases we have to do some computations that involves the function on another input. That “another input” has to get us closer to a base case, or we will never get an answer— similar to how we will never terminate an infinite loop. Determining if a recursive function has a value is as hard as determining if an algorithm terminates, so we cannot check this; we need to guarantee it ourselves. Base cases Recursive case Base case Recursive case If we have a recursive definition, then translating that into a Python function that calculates a value based on it is usually straightforward. Recursive functions work just as you would expect from recursive definitions, and we won’t talk more about how to write recursive functions in this lecture. We will, instead, see how function calls are generally implemented on computers and how this makes recursive functions possible.
  • 3. When we call a recursive function, we start a chain of function calls that (hopefully) eventually hit a base cases where we can get a value. Then, returning from the recursion, we can combine the result of function calls with values in each instance of function calls. We return from the function calls in the reverse order as we made them. Function calls, call stacks, and call stack frames If you have, so far, considered Python functions not much different from mathematical functions—just mappings from input to output—except that they can have side-effects, then this is because it is a useful abstraction. It is a useful way to think about functions and you rarely need to think deeper about them. You will learn something about computers if you try to understand how functions and function calls are implemented on a machine.
  • 4. When you run a computer program, you essentially have a sequence of simple instructions and the CPU can execute them and, when the instructions say so, jump to another point in the instructions. When you call a function, you need to provide it with arguments and reserve space for its local variables. If you want to return from the function again, and the function can be called from more than one location, you need to remember that as well. Caveat: Python runs on a virtual machine, so actually is a little different than explained here, but the concepts are the same. If we have a recursive function, we will have to have several instances of calls to the same function, so we cannot just reserve space for the local variables and return location ones. We have to dynamically do this as needed. (This isn’t just the case for recursive functions but any function that might, through some chain of function calls, be called again before its first call returns).
  • 5. The way computers solve this issue is to have a stack of function calls, or function frames they are sometimes called. When you call a function, you push a return location, space for local variables, and function arguments on the top of the stack. When you then execute the code for the function, you access local variables relative to the stack pointer. If the same function is called more than once, the active one is the one at the top of the stack. When you return from a function call, you remove the call frame from the top of the stack and continue executing from the location you stored in the frame.
  • 6. Tail-recursion A special class of recursive functions are called tail-recursive. Those are functions where the recursive call is the very last thing the function does. It doesn’t do anything with the result of the recursive call except return it. In a chain of tail-recursive calls, all except the first function call will have the same return location. Since we do not modify any local variables after the recursive calls, variables in the frames on the stack will not be modified ever again before they are popped off the stack.
  • 7. In such situations it is possible to optimize away the actual recursion by reusing the call frame of the first function. In many programming languages, this optimization is implemented. Python isn’t as dependent on functions and recursion as other languages, and the optimization is not implemented her. We can always implement it ourselves, though. It sometimes requires a little rewriting to make a function tail-recursive. If there is no more than one recursive call per function, it is relatively easy to do this. If not, it can still be done but it is substantially harder—and not worth the effort in Python. Sometimes it is easier to write a recursive function than an iterative function; if you do this, it is good to know that you can optimize it as well.
  • 8. Often the recursive function is simpler to understand than the iterative one, but if the transformation is the same, then you start to recognize the pattern. If you can write an iterative function straight away, then don’t bother with going through recursion, but often it is easier to think up a recursion first and then do the transformation. The divide and conquer algorithms do this. On this slide, I have written a recursive selection sort and the transformation of it. You can compare it with the iterative selection sort from chapter 5. A very simple divide-and-conquer algorithm is quick sort. It is defined recursively like here, and you will agree that it is a very simple function. (The partition function is a bit more involved but you get to implement it yourself).
  • 9. We cannot get rid of both recursive calls in the tail-recursion transformation, but we can get rid of one of them. If we want to keep the stack depth small —it is a limited resource—we can guarantee that it only grows logarithmic in the input by only recursing on the smaller sub-problem (can you see why the runtime is logarithmic then?) Exercises! Time to put recursion-fu into practice