SlideShare une entreprise Scribd logo
1  sur  80
Télécharger pour lire hors ligne
RecursionExtracted from my lecture during A. Paruj Ratanaworabhan’s
basic preparatory programming course for freshmen:
Introduction to Programming: A Tutorial for New Comers Using Python
By Thai Pangsakulyanont
Software and Knowledge Engineering Undergraduate Student
Kasetsart University
http://greatingpoint.co.th/?
showpage=product&file=product_detail&prd_id=1328776222
Read this sentence and
do what it says twice.
http://programmers.stackexchange.com/a/93858
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
Factorial Example
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
3!
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
We turn this problem into a
smaller problem of same kind.
This is called “decomposition.”
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)! × 1
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)! × 1
= 0! × 1
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)! × 1
= 0! × 1
0! = 1
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)! × 1
= 0! × 1
0! = 1
This is called the “base case”
where the function does not
call itself anymore.
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)! × 1
= 0! × 1
0! = 1
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)! × 1
= 0! × 1
= 1 × 1 = 1
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
1! = (1 - 1)! × 1
= 0! × 1
= 1 × 1 = 1
We use the result of smaller problem
to find the result of larger problem.
This is called “composition”.
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
2! = (2 - 1)! × 2
= 1! × 2
= 1 × 2 = 2
Factorial Example
3!
n! =
(
1 if n = 0
(n 1)! ⇥ n if n > 0
= (3 - 1)! × 3
= 2! × 3
= 2 × 3
= 6.
def fac(n):
if n == 0:
return 1
else:
return fac(n - 1) * n
print fac(12)
Factorial Example
Recursive Function
• A function that calls itself!
Count Down
countdown(5)
print "happy recursion day"
Countdown Algorithm
• If I want to countdown from 0,
then it’s over! Don’t do anything.
• If I want to countdown from N (> 0),
then count N, and countdown from N-1.
Countdown Example
def countdown(n):
if n == 0:
return
print n
countdown(n - 1)
countdown(5)
print "happy recursion day"
Example:
Euclidean Algorithm
• Fast way to find a GCD
of two numbers.
Example:
Euclidean Algorithm
If you have 2 numbers,
then you subtract the smaller number
from the larger number, the GCD of these
two number stays the same.
Example:
Euclidean Algorithm
68 119
GCD(68, 119) is 17
Example:
Euclidean Algorithm
68 119
GCD(68, 51) is still 17
68 51
Example:
Euclidean Algorithm
If you have 2 numbers,
then you subtract the smaller number
from the larger number, the GCD of these
two number stays the same.
Keep doing that until the two numbers
equal each other, then that number is the GCD.
Example:
Euclidean Algorithm
GCD(68, 119)
Example:
Euclidean Algorithm
GCD(68, 119) = GCD(68, 51)
Example:
Euclidean Algorithm
GCD(68, 119) = GCD(68, 51)
= GCD(17, 51)
Example:
Euclidean Algorithm
GCD(68, 119) = GCD(68, 51)
= GCD(17, 51)
= GCD(17, 34)
Example:
Euclidean Algorithm
GCD(68, 119) = GCD(68, 51)
= GCD(17, 51)
= GCD(17, 34)
= GCD(17, 17)
Example:
Euclidean Algorithm
GCD(68, 119) = GCD(68, 51)
= GCD(17, 51)
= GCD(17, 34)
= GCD(17, 17)
= 17
Example:
Euclidean Algorithm
def gcd(a, b):
if a < b:
return gcd(a, b - a)
elif b < a:
return gcd(a - b, b)
else:
return a
print gcd(68, 119)
Who Says It’s Fast?
print gcd(21991144, 21)
# = gcd(21991123, 21)
# = gcd(21991102, 21)
# = gcd(21991081, 21)
# = gcd(21991060, 21)
# = gcd(21991039, 21)
# = gcd(21991018, 21)
# = gcd(21990997, 21)
# = gcd(21990976, 21)
It’s Actually Really Fast
Consider:
(56, 10) → (46, 10) → (36, 10) →
(26, 10) → (16, 10) → (6, 10)
56 % 10 = 6
(the rest of this is for your exercise)
Why Recursion?
• Sometimes it’s easier to write and read
code in recursive form.
Why Recursion?
• Sometimes it’s easier to write and read
code in recursive form.
• You can always convert an iterative
algorithm to recursive and vice versa.
Why Recursion?
• Sometimes it’s easier to write and read
code in recursive form.
• You can always convert an iterative
algorithm to recursive and vice versa.
(does not mean it’s easy)
Iterative
Euclidean Algorithm
def gcd(a, b):
while a != b:
if a < b:
b = b - a
elif b < a:
a = a - b
return a
print gcd(68, 119)
Remember?
• Decomposition
• Base Case
• Composition
String Reversal
• Given a string, I want a reversed version
of that string.
print reverse("reenigne")
# => “engineer”
String Reversal
• Let’s think recursively!
reenigne
Decomposition
r eenigne
Recursive Case
r enginee
eenigne
somehow
Composition
renginee
Composition
engineer
?
eenigne
enginee
e
eenigne
enignee
engine
enginee
Base Case
• The reverse of an empty string is an
empty string.
Recursive Algorithm
reverse(“Hello”)
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = reverse(“lo”) + “l”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = reverse(“lo”) + “l”
reverse(“lo”) = reverse(“o”) + “l”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = reverse(“lo”) + “l”
reverse(“lo”) = reverse(“o”) + “l”
reverse(“o”) = reverse(“”) + “o”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = reverse(“lo”) + “l”
reverse(“lo”) = reverse(“o”) + “l”
reverse(“o”) = reverse(“”) + “o”
reverse(“”) = “”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = reverse(“lo”) + “l”
reverse(“lo”) = reverse(“o”) + “l”
reverse(“o”) = reverse(“”) + “o”
= “” + “o” = “o”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = reverse(“lo”) + “l”
reverse(“lo”) = reverse(“o”) + “l”
= “o” + “l” = “ol”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
reverse(“llo”) = reverse(“lo”) + “l”
= “ol” + “l” = “oll”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
reverse(“ello”) = reverse(“llo”) + “e”
= “oll” + “e” = “olle”
Recursive Algorithm
reverse(“Hello”) = reverse(“ello”) + “H”
= “olle” + “H”
= “olleH”
Reverse Example
def reverse(str):
if str == "":
return str # or return “”
else:
return reverse(str[1:]) + str[0]
print reverse("reenigne")
print sum_digits(314159265) # => 36
Sum of Digits
print sum_digits(314159265) # => 36
Sum of Digits
• NO LOOPS!
• NO STRINGS!
Recursive Algorithm
• Sum of digits of 0 is 0.
• Sum of digits of N > 0:
Find last digit + sum of digits except last.
Recursive Algorithm
• Sum of digits of 0 is 0.
• Sum of digits of N > 0:
Find last digit + sum of digits except last.
N % 10 N // 10
Sum of Digits
def sum_digits(n):
if n == 0:
return 0
else:
return (n % 10) + sum_digits(n // 10)
print sum_digits(314159265)
Palindrome
Civic
Level
Madam
Malayalam
Radar
Reviver
Rotator
Terret
print is_palindrome("Refer") # => True
print is_palindrome("Referrer") # => False
Recursive Algorithm
• Empty string is a palindrome.
• String with 1 character is a palindrome.
• String that has a different first character
and last character is not a palindrome.
Recursive Algorithm
• Empty string is a palindrome.
• String with 1 character is a palindrome.
• String that has a different first character
and last character is not a palindrome.
• String that has a same first and last
character is a palindrome only if the
string without first and last character is a
palindrome.
def is_palindrome(s):
if len(s) < 2:
return True
if s[0].lower() != s[-1].lower():
return False
return is_palindrome(s[1:-1])
print is_palindrome("Refer") # => True
print is_palindrome("Referrer") # => False
def is_palindrome(s):
return reverse(s.lower()) == s.lower()
print is_palindrome("Refer") # => True
print is_palindrome("Referrer") # => False
def reverse(str):
if str == "":
return str
else:
return reverse(str[1:]) + str[0]
Exercise!

Contenu connexe

Tendances

Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
Nikhil Sharma
 

Tendances (20)

Python Modules
Python ModulesPython Modules
Python Modules
 
Python tuple
Python   tuplePython   tuple
Python tuple
 
Iterations and Recursions
Iterations and RecursionsIterations and Recursions
Iterations and Recursions
 
Python list
Python listPython list
Python list
 
Linked list
Linked listLinked list
Linked list
 
Python recursion
Python recursionPython recursion
Python recursion
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Recursion
RecursionRecursion
Recursion
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 

Similaire à Introduction to Recursion (Python)

Chapter 1 review topic in algebra 1
Chapter 1 review topic in algebra 1Chapter 1 review topic in algebra 1
Chapter 1 review topic in algebra 1
jennytuazon01630
 
lecture 1
lecture 1lecture 1
lecture 1
sajinsc
 
Integral Calculus Anti Derivatives reviewer
Integral Calculus Anti Derivatives reviewerIntegral Calculus Anti Derivatives reviewer
Integral Calculus Anti Derivatives reviewer
JoshuaAgcopra
 

Similaire à Introduction to Recursion (Python) (20)

Truth, deduction, computation lecture g
Truth, deduction, computation   lecture gTruth, deduction, computation   lecture g
Truth, deduction, computation lecture g
 
ملزمة الرياضيات للصف السادس الاحيائي الفصل الاول
ملزمة الرياضيات للصف السادس الاحيائي الفصل الاولملزمة الرياضيات للصف السادس الاحيائي الفصل الاول
ملزمة الرياضيات للصف السادس الاحيائي الفصل الاول
 
ملزمة الرياضيات للصف السادس التطبيقي الفصل الاول الاعداد المركبة 2022
 ملزمة الرياضيات للصف السادس التطبيقي الفصل الاول الاعداد المركبة 2022 ملزمة الرياضيات للصف السادس التطبيقي الفصل الاول الاعداد المركبة 2022
ملزمة الرياضيات للصف السادس التطبيقي الفصل الاول الاعداد المركبة 2022
 
Cuaderno de trabajo derivadas experiencia 3
Cuaderno de trabajo  derivadas experiencia 3Cuaderno de trabajo  derivadas experiencia 3
Cuaderno de trabajo derivadas experiencia 3
 
Chapter 1 review topic in algebra 1
Chapter 1 review topic in algebra 1Chapter 1 review topic in algebra 1
Chapter 1 review topic in algebra 1
 
lecture 1
lecture 1lecture 1
lecture 1
 
Asymptotic Notation and Complexity
Asymptotic Notation and ComplexityAsymptotic Notation and Complexity
Asymptotic Notation and Complexity
 
Algorithm.ppt
Algorithm.pptAlgorithm.ppt
Algorithm.ppt
 
Annie
AnnieAnnie
Annie
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Direct solution of sparse network equations by optimally ordered triangular f...
Direct solution of sparse network equations by optimally ordered triangular f...Direct solution of sparse network equations by optimally ordered triangular f...
Direct solution of sparse network equations by optimally ordered triangular f...
 
DAA - UNIT 4 - Engineering.pptx
DAA - UNIT 4 - Engineering.pptxDAA - UNIT 4 - Engineering.pptx
DAA - UNIT 4 - Engineering.pptx
 
CMSC 56 | Lecture 8: Growth of Functions
CMSC 56 | Lecture 8: Growth of FunctionsCMSC 56 | Lecture 8: Growth of Functions
CMSC 56 | Lecture 8: Growth of Functions
 
Integral Calculus Anti Derivatives reviewer
Integral Calculus Anti Derivatives reviewerIntegral Calculus Anti Derivatives reviewer
Integral Calculus Anti Derivatives reviewer
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
 
Scala as a Declarative Language
Scala as a Declarative LanguageScala as a Declarative Language
Scala as a Declarative Language
 
Nbvtalkatbzaonencryptionpuzzles
NbvtalkatbzaonencryptionpuzzlesNbvtalkatbzaonencryptionpuzzles
Nbvtalkatbzaonencryptionpuzzles
 
Nbvtalkatbzaonencryptionpuzzles
NbvtalkatbzaonencryptionpuzzlesNbvtalkatbzaonencryptionpuzzles
Nbvtalkatbzaonencryptionpuzzles
 
Asymptotic analysis
Asymptotic analysisAsymptotic analysis
Asymptotic analysis
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

Introduction to Recursion (Python)