0% found this document useful (0 votes)
41 views

SIC - C - P - DS - Chapter 3 - Unit18 - L

The document discusses recursive functions and algorithms including the Tower of Hanoi puzzle and Fibonacci sequence. It provides definitions and implementations of recursive functions to solve these problems as well as explanations of recursion, memoization, and their applications.

Uploaded by

Ri Riya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

SIC - C - P - DS - Chapter 3 - Unit18 - L

The document discusses recursive functions and algorithms including the Tower of Hanoi puzzle and Fibonacci sequence. It provides definitions and implementations of recursive functions to solve these problems as well as explanations of recursion, memoization, and their applications.

Uploaded by

Ri Riya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Unit learning objective UNIT 18

Unit learning objective UNIT 18


Unit learning objective UNIT 18

Recursive Call Factorial

Fibonacci Sequence memoization


UNIT 18

1.1. How do we make a fractal shape?


ພວກເຮົາສ້າງຮູບຊົງທຄ
ີ່ າ້ ຍຄືຕວ
ົ ເອງແບບຊາໍ້ ຊ້ອນ (fractal shape) ແນວໃດ?
UNIT 18

1.2. Tower of Hanoi problem ບັນຫາຫໍຄອຍຮ່າໂນ້ຍ


UNIT 18

2.1. Solve the Tower of Hanoi puzzle ໄຂປິດສະໜາຫໍຄອຍຮ່າໂນ້ຍ


UNIT 18

2.1. Tower of Hanoi Puzzle Algorithm ຂັັ້ນຕອນວິທປິດສະໜາຫໍຄອຍຮ່າໂນ້ຍ


UNIT 18

3.1. Tower of Hanoi Puzzle Algorithm ຂັັ້ນຕອນວິທປິດສະໜາຫໍຄອຍຮ່າໂນ້ຍ


UNIT 18

3.2. Hanoi() function

('Number {}, {} -> {}' .format(n, from_, to_))

('Number {}, {} -> {}' .format(n, from_, to_))


UNIT 18

3.3. This is how the Tower of Hanoi works. (if n = 3)

('Number {}, {} -> {}' .format(n, from_, to_))

('Number {}, {} -> {}' .format(n, from_, to_))

Number 1, A -> C
Number 2, A -> B
Number 1, C -> B
Number 3, A -> C
Number 1, B -> A
Number 2, B -> C
Number 1, A -> C
UNIT 18

3.4. Programming plan ການວາງແຜນຂຽນໂປຣແກຣມ

Start
[1] Start
hanoi(n, from_, via_, to_)
[2] Call the function hanoi(n, from_, to_, via_)
NO
if number_of_disks_to_move == 1
[3] if there is only one disk then {
[4] Move the disk from from_ to to_} YES

print( ‘Number {}, {} ->


[5] else { Move the (n-1) disks from from_ to to_ {}'.format(number_of_disks_to_move, from_, to_))
Call the function hanoi(n-1, from_, via_, to_)
hanoi(number_of_disks_to_move-1, from_, via_,
[6] Move the largest disk n from_ to_ destination to_)
[7] Move (n-1) disks in via_ to the destination
print(”Number {}, {} ->
from_ is used as an auxiliary rod {}".format(number_of_disks_to_move, from_, to_))

Call the function hanoi(n-1, via_, to_, from_) } hanoi(number_of_disks_to_move-1, via_, to_,
from_)
[8] End
End
UNIT 18

3.5. Tower of Hanoi final code ຫໍຄອຍຮ່າໂນ້ຍ code ສຸດທ້າຍ

('Number {}, {} -> {}' .format(n, from_, to_))

('Number {}, {} -> {}' .format(n, from_, to_))


UNIT 18

1.1. Definition of Factorial


UNIT 18

1.2. Factorial and the for loop

('Enter a number : '))

Enter a number : 5
5! = 120

Line 3, 4
• From 1 to n, the fact variable is multiplied by accumulating by i.
UNIT 18

2.1. What is a recursive function?

def factorial(5):
if n <= 1 :
return 1
else :
return n * factorial(n-1)

5 * factorial(4) return 1 : This process is explained


on the next page
4 * factorial(3)

3 * factorial(2)

2 * factorial(1)
UNIT 18

2.2. The flow of recursive function

factorial(5)

return 5 * factorial(4) = 120

return 4 * factorial(3) = 24

return 3 * factorial(2) = 6

return 2 * factorial(1) = 2

1
UNIT 18

2.2. The flow of recursive function


Focus In a recursive function, the termination condition is absolutely necessary.

# Implement recursive function of n!


# Termination condition is required

# n * (n-1)! implementation by definition


UNIT 18

1. Recursion and Divide-and-Conquer Algorithm


UNIT 18

3.1. Advantages and disadvantages of recursive functions and loop statements

Recursive Functions Loop Statements


Pros Simple code Fast
Use a lot of memory
Cons Complex code
Slow
UNIT 18

3.2. Definition of the Fibonacci sequence

𝐹𝑛 = 𝐹𝑛−1 + 𝐹𝑛−2

• 0, 1, 1, 2, 3, 5, 8, 13, 21,...

Geometric pattern created by the


Fibonacci sequence
UNIT 18

3.2. Definition of the Fibonacci sequence

# A recursive implementation of the Fibonacci function


# Termination condition of the Fibonacci function

("How many Fibonacci numbers do you want?"))

# Cannot find Fibonacci number if it is negative

("Error : Enter a positive number.")

("Fibonacci sequence: ", end=' ')

How many Fibonacci numbers do you want? 5


Fibonacci sequence: 0 1 1 2 3
UNIT 18

3.3. Fibonacci function execution process

fib(5)

fib(4) fib(3)

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

fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)

fib(1) fib(0)
Called Function
UNIT 18

3.4. Implementation of the Fibonacci function

Line 7
• The value is added as it is called recursively until the termination condition is met.
UNIT 18

3.5. Efficiency of implementing the Fibonacci function as a recursive function


UNIT 18

3.6. Fibonacci function and memoization


Focus Memoization is a method of storing the results of small problems that are repeated over and over but the
results do not change.
UNIT 18

3.6. Fibonacci function and memoization

Called Function

Called Function Memoization Function

Function call steps before memoization Function call steps after memoization
UNIT 18

3.7. The Fibonacci function and the principle of memoization


Focus In order to prevent double-counting, if the values of the terms are stored as elements in dic, the values
calculated once do not need to be re-calculated.

Declare a dictionary for memoization as a


# Import all classes and methods of timeit global variable, dic = {0:0, 1:1} Calling
fibonacci_2(1) returns 1, which is dic[1]

If the dictionary already has a computed result, it


returns the result and does not make a recursive call.

If the dictionary has no computed result, the function makes


a recursive call. The call result is stored in a dictionary.
UNIT 18

3.7. The Fibonacci function and the principle of memoization


Focus Learn ​how dictionaries are updated.

The initial dictionary state : dic = {0:0, 1:1}

Call fib(2) : return fib(1) + fib(0)

Call of fib(2) : return dic[0] + dic[1], which


becomes 1
Called Function dic = {0:0, 1:1, 2:1} state updated

Memoization Function
Call fib(3) : return fib(2) + fib(1)

Function call steps after memoization Call fib(3): return dic[1] + dic[2], which becomes 2
dic = {0:0, 1:1, 2:1, 3:2} state updated

...
Try to fully understand the basic concept before moving on to the next step.
Lack of understanding basic concepts will increase your burden in learning this course, which
may make you fail the course.
It may be difficult now, but for successful completion of this course we suggest you to fully
understand the concept and move on to the next step.
UNIT 18

Condition for Enter a number : 10


Execution 55

Time

Write the entire code and the expected output results in the note.
UNIT 18

Enter x : 2
Condition for
Enter n : 10
Execution
1024

Time

Write the entire code and the expected output results in the note.
UNIT 18

1.1. Built-in functions expressed as black boxes ຟັງຊັນໃນຕົວປຽບສະເໝືອນເປັນກ່ອງດາ

input 1 function

input 2 Black Box Output

input 3
UNIT 18

1.1. Built-in functions expressed as black boxes ຟັງຊັນໃນຕົວປຽບສະເໝືອນເປັນກ່ອງດາ

function
input output

‘ABCD’ len() 4
UNIT 18

1.2. Python and built-in functions ພາສາ Python ແລະ ຟັງຊັນໃນຕົວ

Built-in functions in python ຟັງຊັນໃນຕົວໃນພາສາ python


abs dict help min setattr
all dir hex next slice
any divmod id object sorted
ascii enumerate input oct staticmethod
bin eval int open str
bool exec isinstance ord sum
bytearray filter issubclass pow super
bytes float iter print tuple
callable format len property type
chr frozenset list range vars
classmethod getattr locals repr zip
compile globals map reversed _import_
complex hasattr max round
delattr hash memoryview set
UNIT 18

1.3. How to use built-in functions ວິທນາໃຊ້ຟງັ ຊັນໃນຕົວ

# A function that returns an absolute value

# A function that returns the minimum value among multiple elements

# A function that returns the maximum value among multiple elements


UNIT 18

1.4. The return value of a built-in function ການສົງົ່ ຄ່າກັບຄືນຂອງຟັງຊັນໃນຕົວ


# Creates a string object in the format "FOO" or 'FOO‘
# Return the length of a string

# Return the type (type) of an object

# Return the ID value of an object

# Convert strings to numeric values and operators and evaluate them


UNIT 18

1.5. Built-in functions related to sorting

# Sort string

# Sort the list in ascending order

# Sort the list in descending order

Line 1, 2
• The sorted function receives a string and returns the characters that make up the string sorted in alphabetical order.
• The sorted function also has a function to sort and return a list.
• reverse = true to sort in descending order.
UNIT 18

1.6. The id function and object-oriented programming


UNIT 18

1.7. type function


UNIT 18

1.8. eval function

# The Python translator executes the sentence of 10 + 20

# The Python translator executes the sentence of (5 * 20) / 2

# The Unicode value 65 is the alphabet ‘A’, which the chr() function returns

# Return the Unicode value 65 of the alphabet ‘A’


UNIT 18

2.1. Step-by-step execution process

‣ Solve the Tower of Hanoi problem using recursive


functions.
‣ Consider a simple case with three disks as shown in the
figure. In the final stage, the largest disk (red disk) must
go from A to C.
‣ To do that, both the middle disk (blue disk) and the small
disk (green disk) must go to B.
‣ It should be considered to move the two disks to the
destination B using the starting point A and the auxiliary
rod C without considering the large disk.
‣ When all the smaller disks have been moved to B, the
largest disk is moved to C. [Figure 3]
‣ In this case, there will be two small disks on rod B.
[Figure 4]
‣ After that, it should be considered to move the two small
disks from the starting point B to the destination C using
the auxiliary rod A. [Figure 5, 6, 7]
UNIT 18

2.1. Step-by-step execution process


UNIT 18

2.2. Tower of Hanoi Algorithm ຂັັ້ນຕອນວິທຂອງຫໍຄອຍຮ່າໂນ້ຍ

("Number {}, {} -> {}".format(n, from_, to_))


UNIT 18
UNIT 18
UNIT
18

Output example
eular(20) = 2.71828

You might also like