Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
133 views

Python Recursion

The document discusses recursive functions and provides examples of recursive algorithms. It begins by explaining how the factorial function can be written iteratively or recursively. It then provides more examples of recursive algorithms, including computing the greatest common divisor (GCD) of two numbers, calculating Fibonacci numbers, and solving the Towers of Hanoi problem. The key aspects of recursive functions are that they call themselves to break down large problems into smaller subproblems until a base case is reached.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
133 views

Python Recursion

The document discusses recursive functions and provides examples of recursive algorithms. It begins by explaining how the factorial function can be written iteratively or recursively. It then provides more examples of recursive algorithms, including computing the greatest common divisor (GCD) of two numbers, calculating Fibonacci numbers, and solving the Towers of Hanoi problem. The key aspects of recursive functions are that they call themselves to break down large problems into smaller subproblems until a base case is reached.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Python: Recursive Functions

Recursive Functions

Recall factorial function:


Iterative Algorithm

Loop construct (while) can


capture computation in a set of
state variables that update
on each iteration
through loop
Recursive Functions

Alternatively:
Consider

5! =
5x4x3x2x1
can be re-
written as 5!
=5x4!
factorial(n) = n * factorial(n-1)
In general
n! = nx(n-1)!
Recursive Functions

Alternatively:
Consider

5! = 5x4x3x2x1 Recursive Algorithm


can be re-written as 5!=5x4!
function calling itself
In general n! = nx(n-1)!

factorial(n) = n * factorial(n-1)
Recursive Functions
Recursive Functions

Known
Base case
Recursive Functions

Base case

Recursive step
Recursive Functions

• No computation in first
phase, only function calls
• Deferred/Postponed fact (4)
4 * fact (3)
computation 4 * (3 * fact (2))
4 * (3 * (2 * fact (1)))
– after function calls 4 * (3 * (2 * (1 * fact (0))))
terminate, computation 4 * (3 * (2 * (1 * 1)))
4 * (3 * (2 * 1))
starts 4 * (3 * 2)
• Sequence of calls have 4*6
24
to be remembered Execution trace for n = 4
Courtesy Prof PR Panda CSE Department IIT Dehi
Another Example (Iterative)

Iterative

Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Another Example (Recursive)

Iterative Algorithm
Recursive

Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Recursive Functions
• Size of the problem reduces at each step
• The nature of the problem remains the same
• There must be at least one terminating condition

• Simpler, more intuitive


– For inductively defined computation, recursive algorithm
may be natural
• close to mathematical specification
• Easy from programing point of view
• May not efficient computation point of view
GCD Algorithm

b if a mod b = 0
gcd (a, b) =
gcd (b, a mod b) otherwise

Iterative Recursive
Algorithm Algorithm
GCD Algorithm

b if a mod b = 0
gcd (a, b) =
gcd (b, a mod b) otherwise

gcd (6, 10)


gcd (10, 6)
gcd (6, 4)
gcd (4, 2)
2
2
2
2
Courtesy Prof PR Panda CSE Department IIT Dehi
Fibonacci Numbers

0 n=1
fib (n) = 1 n=2
fib (n-1) + fib (n-2) n > 2

Recursive
Algorithm

Courtesy Prof PR Panda CSE Department IIT Dehi


Fibonacci Numbers

fib (6)

fib (5) fib (4)

fib (4) fib (3) fib (3) fib (2)

fib (3) fib (2) fib (2) fib (1) fib (2) fib (1)

fib (2) fib (1)

Courtesy Prof PR Panda CSE Department IIT Dehi


Power Function
• Write a function power (x,n) to compute the nth
power of x

1 if n = 0
power(x,n) =
x * power(x,n-1) otherwise
Power Function
• Efficient power function

• Fast Power
– fpower(x,n) = 1 for n = 0
– fpower(x,n) = x * (fpower(x, n/2))2 if n is odd
– fpower(x,n) = (fpower(x, n/2))2 if n is even
Power Function
• Efficient power function
Towers of Hanoi Problem
• 64 gold discs with different
diameters
• Three poles: (Origin, Spare, Final)
• Transfer all discs to final pole
from origin
– one at a time
– spare can be used to temporarily
store discs Origin Spare Final
– no disk should be placed on a
smaller disk
• Intial Arrangement:
– all on origin pole, largest at bottom,
next above it, etc.
Courtesy Prof PR Panda CSE Department IIT Dehi
3-Step Strategy

Origin Spare Final Origin Spare Final


Solve for (n-1) disks. Move to Spare.
Use Final as Spare.

Origin Spare Final Origin Spare Final


Move (n-1) disks to Final.
Move bottom disk to Final
Courtesy Prof PR Panda CSE Department IIT Dehi
Use Origin as Spare.
Recursive Solution

• Use algorithm for (n-1) disks to solve n-disk problem


• Use algorithm for (n-2) disks to solve (n-1) disk problem
• Use algorithm for (n-3) disks to solve (n-2) disk problem
• ...
• Finally, solve 1-disk problem:
– Just move the disk!

Courtesy Prof PR Panda CSE Department IIT Dehi


Problem solving with Top Down Design
 Top down design approach, also called as Stepwise refinement, is essential to
develop a well structured program.
 This approach is a problem solving technique that systematically breaks a
complicated problem into smaller, more manageable pieces.
 If any of these subproblems is not easier to solve, we further divide the
subproblem into smaller parts.
 We repeat the subdividing process until all small parts are not dividable.
 Then, we can use a few lines of code to solve every trivial problem. In the end,
we put all these little pieces together as a solution to the original problem.
 This approach makes it easy to think about the problem, code the solution read
the code and identify bugs.
Steps to solve a problem using Top
Down Design:

1. Start with an initial problem statement.


2. Define subtask at the first level.
3. Divide subtasks at a higher level into more
specific tasks.
4. Repeat step (3) until each subtask is trivial.
5. Refine the algorithm into real code.
Business requirement Analysis
Initial Problem statement
Read new emails from an email box and save email messages into a database table.
Case study: Gathering Information
from a file system
Import os
os.mkdir(“d:\\tempdir”)
FILES

Open( )
Syntax
file_object = (“filename.txt”, “Access Mode”)

File pointer

points to the content of file


Access Modes
r – read mode
only for reading the content
file pointer points at the beginning of the file
file should exist before opening in read mode

You might also like