SlideShare a Scribd company logo
1 of 59
RECURSION
Part 2
Primarily, there are two types of recursive functions. Functions that call itself or two functions that call
each other mutually. The functions that call itself are direct recursive and when two functions call each
other mutually, then those functions are called indirect recursive functions.
Types of Recursive functions
DIRECT RECURSIVE FUNCTIONS
These functions are the same recursive functions that you have been learning till now. When
a function calls the same function again, you call it a direct function. Factorial is an example
of direct recursive .
INDIRECT RECURSIVE FUNCTIONS
In Indirect recursive functions, two functions mutually call each other wherein both the functions must
have a base case. Let's understand using a flowchart.
Here, function1 calls function2 which in turn calls function1.
STRING REVERSAL
• Given a string, I want a reversed version of that string.
print reverse(“Arial")
# => “lairA”
BASE CASE
The reverse of an empty string is an
empty string.
Recursive Algorithm
reverse(“Arial”)
Recursive Algorithm
reverse(“Arial”) = reverse(“rial”) + “A”
RECURSIVE ALGORITHM
reverse(“Arial”) = reverse(“rial”) + “A”
reverse(“rial”) = reverse(“ial”) + “r”
RECURSIVE ALGORITHM
reverse(“Arial”) = reverse(“rial”) + “A”
reverse(“rial”) = reverse(“ial”) + “r”
reverse(“ial”) = reverse(“al”) + “i”
RECURSIVE ALGORITHM
reverse(“Arial”) = reverse(“rial”) + “A”
reverse(“rial”) = reverse(“ial”) + “r”
reverse(“ial”) = reverse(“al”) + “i”
reverse(“al”) = reverse(“l”) + “a”
RECURSIVE ALGORITHM
reverse(“Arial”) = reverse(“rial”) + “A”
reverse(“rial”) = reverse(“ial”) + “r”
reverse(“ial”) = reverse(“al”) + “i”
reverse(“al”) = reverse(“l”) + “a”
reverse(“l”) = reverse(“”) + “l”
RECURSIVE ALGORITHM
reverse(“Arial”) = reverse(“rial”) + “A”
reverse(“rial”) = reverse(“ial”) + “r”
reverse(“ial”) = reverse(“al”) + “i”
reverse(“al”) = reverse(“l”) + “a”
reverse(“l”) = reverse(“”) + “l”
reverse(“”) = “”
RECURSIVE ALGORITHM
reverse(“Arial”) = reverse(“rial”) + “A”
reverse(“rial”) = reverse(“ial”) + “r”
reverse(“ial”) = reverse(“al”) + “i”
reverse(“al”) = reverse(“l”) + “a”
reverse(“l”) = reverse(“”) + “l”
= “” + “l” = “l”
RECURSIVE ALGORITHM
reverse(“Arial”) = reverse(“rial”) + “A”
reverse(“rial”) = reverse(“ial”) + “r”
reverse(“ial”) = reverse(“al”) + “i”
reverse(“al”) = reverse(“l”) + “a”
= “l” + “a” = “la”
RECURSIVE ALGORITHM
reverse(“Arial”) = reverse(“rial”) + “A”
reverse(“rial”) = reverse(“ial”) + “r”
reverse(“ial”) = reverse(“al”) + “i”
= “la” + “i” = “lai”
RECURSIVE ALGORITHM
reverse(“Arial”) = reverse(“rial”) + “A”
reverse(“rial”) = reverse(“ial”) + “r”
= “lai” + “r” = “lair”
RECURSIVE ALGORITHM
reverse(“Arial”) = reverse(“rial”) + “A”
= “lair” + “A”
= “lairA”
REVERSE EXAMPLE
def reverse(str):
if str == "":
return str # or return “”
else:
return reverse(str[1:]) + str[0]
print reverse("welcome")
print sum_digits(314159265) # => 36
Sum of Digits
print sum_digits(314159265) # => 36
•NO LOOPS!
•NO STRINGS!
SUM OF DIGITS
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)
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
68 51
GCD(68, 51) is still 17
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
return gcd(a, b - a)
elif b < a:
return gcd(a - b, b)
else:
return a
print gcd(68, 119)
def gcd(a, b):
if a< b:
ITERATIVE EUCLIDEAN ALGORITHM
return a
print gcd(68, 119)
def gcd(a, b):
while a != b:
if a < b:
b = b - a
elif b < a:
a = a - b
WHO SAYS IT’S FAST?
print gcd(31961144,21)
# = gcd(31960976, 21)
# = gcd(31960955, 21)
# = gcd(31961123, 21)
# = gcd(31961102, 21)
# = gcd(31961081, 21)
# = gcd(31961060, 21)
# = gcd(31961039, 21)
#
#
=
=
gcd(31961018,
gcd(31960997,
21)
21)
It ’s Actually Really Fast
Consider:
(56, 10) → (46, 10) → (36, 10) →
(26, 10) → (16, 10) → (6, 10)
56 % 10 = 6
# Python program to find the H.C.F of two input number
# define a function
def computeHCF(x, y):
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first
number:"))
b=int(input("Enter second
number:"))
GCD=gcd(a,b)
print("GCD is: ") print(GCD)
RECURSION - PROGRAM
PALINDROME
Civic
Level
Madam
Malayala
m Radar
Reviver
Rotator
Terret
print is_palindrome("Refer") # => True
print is_palindrome("Referrer") # => Fals
e
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 reverse(str):
if str == "":
return str
else:
return reverse(str[1:]) + str[0]
def is_palindrome(s):
return reverse(s.lower()) == s.lower()
print is_palindrome("Refer") # => True
print is_palindrome("Referrer") # => False
Fibonacci numbers Using Recursion
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, …
Algorithm
Fib(n)
1. If n =1 or n=2, then
2. return 1
3. Else
4. a = Fib(n-1)
5. b = Fib(n-2)
6. return a+b
Fibonacci numbers Using Recursion
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, …
Program
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
nterms = int(input("enter a number"))
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fib(i))
Binary Search Using Recursion
Algorithm
1. Find the midpoint of the array; this will be the element
at arr[size/2]. The midpoint divides the array into two
smaller arrays: lower half and upper half
2. Compare key to arr[midpoint] by calling the
user function cmp_proc.
3. If the key is a match, return arr[midpoint]; otherwise
4. If the array consists of only one element return NULL,
indicating that there is no match; otherwise
5. If the key is less than the value extracted
from arr[midpoint] search the lower half of the
array by recursively calling search; otherwise
6. Search the upper half of the array by
recursively
calling search.
NOTE:- For binary search all elements must be in order.
Binary Search Using Recursion
Program
def binarySearch (arr, first, last, x):
if last >= first:
mid =int( first + (last - first)/2)
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr, first, mid-1, x)
else:
return binarySearch(arr, mid+1, last, x)
else:
return -1
arr = [ 1,3,5,6,7,8,10,13,14 ]
x = 10
result = binarySearch(arr, 0, len(arr)-1, x)
if result != -1:
print ("Element is present at index %d" % result)
else:
print ("Element is not present in array")
ITERATION VS RECURSION
• The concept of recursion and iteration is pretty much the same. Both execute a set of instructions repeatedly to achieve
the desired output, but only the methodology differs.
• Simply said, recursive functions call itself during its execution, enabling the function to repeat itself several times.
• Whereas iterative functions follow a set of instructions, these instructions are repeated in a sequence a specified number of
times or until a condition is met.
ITERATION VS RECURSION
• Recursive functions are commonly used in computer science because they allow programmers to write efficient programs
using a minimal amount of code. The downside is that they can cause infinite loops and other unexpected results if not
written properly. This is one of the core difference between iterative and recursive functions.
• Iterative functions are the best bet when time complexity is an issue because the number of iterations is defined or can be
easily defined, which is not the case for recursive functions.
• The recursive function has a relatively smaller and shorter code than the iterative function.
ITERATION VS RECURSION
# ----- Recursion -----
# Method to find factorial of given number
using a recursion function
• def recursive_factorial(n):
if (n == 0):
return 1
return n * recursive_factorial(n - 1)
# ----- Iteration -----
# Method to find the factorial of a given
number using an iteration function
• def iterative_factorial(n):
product = 1
for i in range(1, n + 1):
product = product * i
return product
RECURSION VS ITERATION
● Advantages
○ It can reduce time complexity
○ It adds clarity and reduce your time to write and
debug the code
○ It is better in problem based on
tree traversals / structures
● Disadvantages
○ It uses more memory for the stack
○ It can be slow, due to the overhead of maintaining
stack
1 Recursive Python function to find sum of natural numbers.
2. Recursive Python function to find sum of even numbers.
3. Recursive Python function to find sum of odd numbers.
4. Recursive Python function to find sum of fib series.
5. Recursive Python function to find given number is prime or not.
6. Write and test a recursive function max to find the largest number
in a list(array of numbers).
EXERCISE
THANK YOU
Presented by
KIRTI GUPTA
PGT CS
KV NTPC DADRI

More Related Content

What's hot

An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellMichel Rijnders
 
5.1 anti derivatives
5.1 anti derivatives5.1 anti derivatives
5.1 anti derivativesmath265
 
Functional programming from its fundamentals
Functional programming from its fundamentalsFunctional programming from its fundamentals
Functional programming from its fundamentalsMauro Palsgraaf
 
1.4 the basic language of functions
1.4 the basic language of functions1.4 the basic language of functions
1.4 the basic language of functionsmath123c
 
5.2 the substitution methods
5.2 the substitution methods5.2 the substitution methods
5.2 the substitution methodsmath265
 
The Algebric Functions
The Algebric FunctionsThe Algebric Functions
The Algebric Functionsitutor
 
Functions and graphs
Functions and graphsFunctions and graphs
Functions and graphsSujata Tapare
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...ssuserd6b1fd
 
Dataflow Analysis
Dataflow AnalysisDataflow Analysis
Dataflow AnalysisMiller Lee
 
5.5 Injective and surjective functions. Dynamic slides.
5.5 Injective and surjective functions. Dynamic slides.5.5 Injective and surjective functions. Dynamic slides.
5.5 Injective and surjective functions. Dynamic slides.Jan Plaza
 
Algebraic functions powerpoint
Algebraic functions powerpointAlgebraic functions powerpoint
Algebraic functions powerpointCaron White
 
5.3 areas, riemann sums, and the fundamental theorem of calaculus
5.3 areas, riemann sums, and the fundamental theorem of calaculus5.3 areas, riemann sums, and the fundamental theorem of calaculus
5.3 areas, riemann sums, and the fundamental theorem of calaculusmath265
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expressionMegha V
 

What's hot (17)

An Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using HaskellAn Introduction to Functional Programming using Haskell
An Introduction to Functional Programming using Haskell
 
5.1 anti derivatives
5.1 anti derivatives5.1 anti derivatives
5.1 anti derivatives
 
Functional programming from its fundamentals
Functional programming from its fundamentalsFunctional programming from its fundamentals
Functional programming from its fundamentals
 
1.4 the basic language of functions
1.4 the basic language of functions1.4 the basic language of functions
1.4 the basic language of functions
 
5.2 the substitution methods
5.2 the substitution methods5.2 the substitution methods
5.2 the substitution methods
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Functions
FunctionsFunctions
Functions
 
The Algebric Functions
The Algebric FunctionsThe Algebric Functions
The Algebric Functions
 
Functions and graphs
Functions and graphsFunctions and graphs
Functions and graphs
 
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
Think Like Scilab and Become a Numerical Programming Expert- Notes for Beginn...
 
Function
Function Function
Function
 
Dataflow Analysis
Dataflow AnalysisDataflow Analysis
Dataflow Analysis
 
5.5 Injective and surjective functions. Dynamic slides.
5.5 Injective and surjective functions. Dynamic slides.5.5 Injective and surjective functions. Dynamic slides.
5.5 Injective and surjective functions. Dynamic slides.
 
Algebraic functions powerpoint
Algebraic functions powerpointAlgebraic functions powerpoint
Algebraic functions powerpoint
 
5.3 areas, riemann sums, and the fundamental theorem of calaculus
5.3 areas, riemann sums, and the fundamental theorem of calaculus5.3 areas, riemann sums, and the fundamental theorem of calaculus
5.3 areas, riemann sums, and the fundamental theorem of calaculus
 
Functions
FunctionsFunctions
Functions
 
Python- Regular expression
Python- Regular expressionPython- Regular expression
Python- Regular expression
 

Similar to Recursion part 2

Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo Herrero
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
Implement the following sorting algorithms  Bubble Sort  Insertion S.pdfImplement the following sorting algorithms  Bubble Sort  Insertion S.pdf
Implement the following sorting algorithms Bubble Sort Insertion S.pdfkesav24
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)Thai Pangsakulyanont
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskellgoncharenko
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lessonteach4uin
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Leonardo Borges
 
The Magnificent Seven
The Magnificent SevenThe Magnificent Seven
The Magnificent SevenMike Fogus
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScriptJoseph Smith
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaDaniel Cukier
 

Similar to Recursion part 2 (20)

Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Monadologie
MonadologieMonadologie
Monadologie
 
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
Implement the following sorting algorithms  Bubble Sort  Insertion S.pdfImplement the following sorting algorithms  Bubble Sort  Insertion S.pdf
Implement the following sorting algorithms Bubble Sort Insertion S.pdf
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Stdlib functions lesson
Stdlib functions lessonStdlib functions lesson
Stdlib functions lesson
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Lecture9 recursion
Lecture9 recursionLecture9 recursion
Lecture9 recursion
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015Parametricity - #cljsyd - May, 2015
Parametricity - #cljsyd - May, 2015
 
The Magnificent Seven
The Magnificent SevenThe Magnificent Seven
The Magnificent Seven
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
Java - Operators
Java - OperatorsJava - Operators
Java - Operators
 
Java 2
Java 2Java 2
Java 2
 
LMD UGR
LMD UGRLMD UGR
LMD UGR
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 

More from Keerty Smile

Insight into progam execution ppt
Insight into progam execution pptInsight into progam execution ppt
Insight into progam execution pptKeerty Smile
 
Data file handling in python binary & csv files
Data file handling in python binary & csv filesData file handling in python binary & csv files
Data file handling in python binary & csv filesKeerty Smile
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methodsKeerty Smile
 
Data file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing filesData file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing filesKeerty Smile
 

More from Keerty Smile (7)

Insight into progam execution ppt
Insight into progam execution pptInsight into progam execution ppt
Insight into progam execution ppt
 
Data file handling in python binary & csv files
Data file handling in python binary & csv filesData file handling in python binary & csv files
Data file handling in python binary & csv files
 
Data file handling in python reading & writing methods
Data file handling in python reading & writing methodsData file handling in python reading & writing methods
Data file handling in python reading & writing methods
 
Data file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing filesData file handling in python introduction,opening &amp; closing files
Data file handling in python introduction,opening &amp; closing files
 
Keerty rdbms sql
Keerty rdbms sqlKeerty rdbms sql
Keerty rdbms sql
 
Computer networks
Computer networksComputer networks
Computer networks
 
Recursion part 1
Recursion part 1Recursion part 1
Recursion part 1
 

Recently uploaded

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 

Recently uploaded (20)

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

Recursion part 2

  • 2. Primarily, there are two types of recursive functions. Functions that call itself or two functions that call each other mutually. The functions that call itself are direct recursive and when two functions call each other mutually, then those functions are called indirect recursive functions. Types of Recursive functions
  • 3. DIRECT RECURSIVE FUNCTIONS These functions are the same recursive functions that you have been learning till now. When a function calls the same function again, you call it a direct function. Factorial is an example of direct recursive .
  • 4. INDIRECT RECURSIVE FUNCTIONS In Indirect recursive functions, two functions mutually call each other wherein both the functions must have a base case. Let's understand using a flowchart. Here, function1 calls function2 which in turn calls function1.
  • 5. STRING REVERSAL • Given a string, I want a reversed version of that string. print reverse(“Arial") # => “lairA”
  • 6. BASE CASE The reverse of an empty string is an empty string.
  • 8. Recursive Algorithm reverse(“Arial”) = reverse(“rial”) + “A”
  • 9. RECURSIVE ALGORITHM reverse(“Arial”) = reverse(“rial”) + “A” reverse(“rial”) = reverse(“ial”) + “r”
  • 10. RECURSIVE ALGORITHM reverse(“Arial”) = reverse(“rial”) + “A” reverse(“rial”) = reverse(“ial”) + “r” reverse(“ial”) = reverse(“al”) + “i”
  • 11. RECURSIVE ALGORITHM reverse(“Arial”) = reverse(“rial”) + “A” reverse(“rial”) = reverse(“ial”) + “r” reverse(“ial”) = reverse(“al”) + “i” reverse(“al”) = reverse(“l”) + “a”
  • 12. RECURSIVE ALGORITHM reverse(“Arial”) = reverse(“rial”) + “A” reverse(“rial”) = reverse(“ial”) + “r” reverse(“ial”) = reverse(“al”) + “i” reverse(“al”) = reverse(“l”) + “a” reverse(“l”) = reverse(“”) + “l”
  • 13. RECURSIVE ALGORITHM reverse(“Arial”) = reverse(“rial”) + “A” reverse(“rial”) = reverse(“ial”) + “r” reverse(“ial”) = reverse(“al”) + “i” reverse(“al”) = reverse(“l”) + “a” reverse(“l”) = reverse(“”) + “l” reverse(“”) = “”
  • 14. RECURSIVE ALGORITHM reverse(“Arial”) = reverse(“rial”) + “A” reverse(“rial”) = reverse(“ial”) + “r” reverse(“ial”) = reverse(“al”) + “i” reverse(“al”) = reverse(“l”) + “a” reverse(“l”) = reverse(“”) + “l” = “” + “l” = “l”
  • 15. RECURSIVE ALGORITHM reverse(“Arial”) = reverse(“rial”) + “A” reverse(“rial”) = reverse(“ial”) + “r” reverse(“ial”) = reverse(“al”) + “i” reverse(“al”) = reverse(“l”) + “a” = “l” + “a” = “la”
  • 16. RECURSIVE ALGORITHM reverse(“Arial”) = reverse(“rial”) + “A” reverse(“rial”) = reverse(“ial”) + “r” reverse(“ial”) = reverse(“al”) + “i” = “la” + “i” = “lai”
  • 17. RECURSIVE ALGORITHM reverse(“Arial”) = reverse(“rial”) + “A” reverse(“rial”) = reverse(“ial”) + “r” = “lai” + “r” = “lair”
  • 18. RECURSIVE ALGORITHM reverse(“Arial”) = reverse(“rial”) + “A” = “lair” + “A” = “lairA”
  • 19. REVERSE EXAMPLE def reverse(str): if str == "": return str # or return “” else: return reverse(str[1:]) + str[0] print reverse("welcome")
  • 20. print sum_digits(314159265) # => 36 Sum of Digits
  • 21. print sum_digits(314159265) # => 36 •NO LOOPS! •NO STRINGS! SUM OF DIGITS
  • 22. RECURSIVE ALGORITHM •Sum of digits of 0 is 0. •Sum of digits of N > 0: Find last digit + sum of digits except last.
  • 23. 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
  • 24. SUM OF DIGITS def sum_digits(n): if n == 0: return 0 else: return (n % 10) + sum_digits(n // 10) print sum_digits(314159265)
  • 26. 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.
  • 27. Countdown Example def countdown(n): if n ==0: return print n countdown(n - 1) countdown(5) print"happy recursion day"
  • 28. Example: Euclidean Algorithm • Fast way to find a GCD of two numbers.
  • 29. 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.
  • 30. Example: Euclidean Algorithm (68 ,119) GCD(68, 119) is 17
  • 31. EXAMPLE: Euclidean Algorithm 68 119 68 51 GCD(68, 51) is still 17
  • 32. 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.
  • 35. Example: Euclidean Algorithm GCD(68, 119) = GCD(68, 51) = GCD(17, 51)
  • 36. Example: Euclidean Algorithm GCD(68, 119) = GCD(68, 51) = GCD(17, 51) = GCD(17, 34)
  • 37. Example: Euclidean Algorithm GCD(68, 119) = GCD(68, 51) = GCD(17, 51) = GCD(17, 34) = GCD(17, 17)
  • 38. Example: Euclidean Algorithm GCD(68, 119) = GCD(68, 51) = GCD(17, 51) = GCD(17, 34) = GCD(17, 17) = 17
  • 39. EXAMPLE: EUCLIDEAN ALGORITHM return gcd(a, b - a) elif b < a: return gcd(a - b, b) else: return a print gcd(68, 119) def gcd(a, b): if a< b:
  • 40. ITERATIVE EUCLIDEAN ALGORITHM return a print gcd(68, 119) def gcd(a, b): while a != b: if a < b: b = b - a elif b < a: a = a - b
  • 41. WHO SAYS IT’S FAST? print gcd(31961144,21) # = gcd(31960976, 21) # = gcd(31960955, 21) # = gcd(31961123, 21) # = gcd(31961102, 21) # = gcd(31961081, 21) # = gcd(31961060, 21) # = gcd(31961039, 21) # # = = gcd(31961018, gcd(31960997, 21) 21)
  • 42. It ’s Actually Really Fast Consider: (56, 10) → (46, 10) → (36, 10) → (26, 10) → (16, 10) → (6, 10) 56 % 10 = 6
  • 43. # Python program to find the H.C.F of two input number # define a function def computeHCF(x, y): # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf def gcd(a,b): if(b==0): return a else: return gcd(b,a%b) a=int(input("Enter first number:")) b=int(input("Enter second number:")) GCD=gcd(a,b) print("GCD is: ") print(GCD) RECURSION - PROGRAM
  • 45. print is_palindrome("Refer") # => True print is_palindrome("Referrer") # => Fals e
  • 46. 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.
  • 47. 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.
  • 48. 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
  • 49. def reverse(str): if str == "": return str else: return reverse(str[1:]) + str[0] def is_palindrome(s): return reverse(s.lower()) == s.lower() print is_palindrome("Refer") # => True print is_palindrome("Referrer") # => False
  • 50. Fibonacci numbers Using Recursion 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, … Algorithm Fib(n) 1. If n =1 or n=2, then 2. return 1 3. Else 4. a = Fib(n-1) 5. b = Fib(n-2) 6. return a+b
  • 51. Fibonacci numbers Using Recursion 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, … Program def fib(n): if n <= 1: return n else: return(fib(n-1) + fib(n-2)) nterms = int(input("enter a number")) if nterms <= 0: print("Plese enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print(fib(i))
  • 52. Binary Search Using Recursion Algorithm 1. Find the midpoint of the array; this will be the element at arr[size/2]. The midpoint divides the array into two smaller arrays: lower half and upper half 2. Compare key to arr[midpoint] by calling the user function cmp_proc. 3. If the key is a match, return arr[midpoint]; otherwise 4. If the array consists of only one element return NULL, indicating that there is no match; otherwise 5. If the key is less than the value extracted from arr[midpoint] search the lower half of the array by recursively calling search; otherwise 6. Search the upper half of the array by recursively calling search. NOTE:- For binary search all elements must be in order.
  • 53. Binary Search Using Recursion Program def binarySearch (arr, first, last, x): if last >= first: mid =int( first + (last - first)/2) if arr[mid] == x: return mid elif arr[mid] > x: return binarySearch(arr, first, mid-1, x) else: return binarySearch(arr, mid+1, last, x) else: return -1 arr = [ 1,3,5,6,7,8,10,13,14 ] x = 10 result = binarySearch(arr, 0, len(arr)-1, x) if result != -1: print ("Element is present at index %d" % result) else: print ("Element is not present in array")
  • 54. ITERATION VS RECURSION • The concept of recursion and iteration is pretty much the same. Both execute a set of instructions repeatedly to achieve the desired output, but only the methodology differs. • Simply said, recursive functions call itself during its execution, enabling the function to repeat itself several times. • Whereas iterative functions follow a set of instructions, these instructions are repeated in a sequence a specified number of times or until a condition is met.
  • 55. ITERATION VS RECURSION • Recursive functions are commonly used in computer science because they allow programmers to write efficient programs using a minimal amount of code. The downside is that they can cause infinite loops and other unexpected results if not written properly. This is one of the core difference between iterative and recursive functions. • Iterative functions are the best bet when time complexity is an issue because the number of iterations is defined or can be easily defined, which is not the case for recursive functions. • The recursive function has a relatively smaller and shorter code than the iterative function.
  • 56. ITERATION VS RECURSION # ----- Recursion ----- # Method to find factorial of given number using a recursion function • def recursive_factorial(n): if (n == 0): return 1 return n * recursive_factorial(n - 1) # ----- Iteration ----- # Method to find the factorial of a given number using an iteration function • def iterative_factorial(n): product = 1 for i in range(1, n + 1): product = product * i return product
  • 57. RECURSION VS ITERATION ● Advantages ○ It can reduce time complexity ○ It adds clarity and reduce your time to write and debug the code ○ It is better in problem based on tree traversals / structures ● Disadvantages ○ It uses more memory for the stack ○ It can be slow, due to the overhead of maintaining stack
  • 58. 1 Recursive Python function to find sum of natural numbers. 2. Recursive Python function to find sum of even numbers. 3. Recursive Python function to find sum of odd numbers. 4. Recursive Python function to find sum of fib series. 5. Recursive Python function to find given number is prime or not. 6. Write and test a recursive function max to find the largest number in a list(array of numbers). EXERCISE
  • 59. THANK YOU Presented by KIRTI GUPTA PGT CS KV NTPC DADRI