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

Chapter 3 - Algorithms Part I

python

Uploaded by

Duc Vuong Nguyen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Chapter 3 - Algorithms Part I

python

Uploaded by

Duc Vuong Nguyen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

EE3491 – KỸ THUẬT LẬP TRÌNH

PROGRAMMING TECHNIQUES

CHAPTER 3
Algorithms – Part I
Võ Duy Thành
Department of Automation Engineering
Control Technique and Innovation Lab. for Electric Vehicles
School of Electrical and Electronic Engineering
Hanoi University of Science and Technology
[email protected] | [email protected]
Outline

1. What is Algorithm
2. Examples
3. Algorithm Complexity
4. Fundamental Algorithms
5. Recursion

2
1. What is algorithm | 1.1. Definition

• An algorithm is a well-defined sequential computational technique that


accepts a value or a collection of values as input and produces the
output(s) needed to solve a problem.
• Or an algorithm procedure mapping each input to a single output.
• An algorithm is to solve a computational problem
• Algorithm solves a problem if it returns a correct output for every problem input
• An algorithm is said to be accurate if and only if it stops with the proper output
for each input instance

Mission
accomplished!
Problem is solved.

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 3


1. What is algorithm | 1.1. Definition

• Why algorithm?
• Efficiency: Algorithms can perform tasks quickly and accurately.
• Consistency: Algorithms are repeatable and produce consistent results every
time they are executed.
• Scalability: Algorithms can be scaled up to handle large datasets or complex
problems.
• Automation: Algorithms can automate repetitive tasks, reducing the need for
human intervention and freeing up time for other tasks.
• Standardization: Algorithms can be standardized and shared among different
teams or organizations.

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 4


1. What is algorithm | 1.2. Classification

• Fundamental types of algorithm: No matter what the complexity is,


• Sorting algorithms a big problem can be divided into subproblems
• Bubble sort, Insertion sort, Merge sort, … which are solved by fundamental algorithms
• Searching algorithms
• Linear search, Bisectional search, Interpolation
search
Remember:
• Graph algorithms Divide and Conquer
• Shortest path algorithm Minimum spanning
tree/Maximum flow algorithms, Network flow
algorithm
• Optimization algorithms
• Greedy, Dynamic programming
• and many more

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 5


1. What is algorithm | 1.3. Characteristics

• Properties of algorithms
Clear and
• Terminates at finite time Unambiguous

• Produce at least one output


• Take zero or more inputs Effectiveness
Well-defined
inputs,
• Produce same output with same outputs

input case
• Each step must be effective, i.e. Algorithms
every step should do some works
Language
Finiteness
independent

Feasible

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 6


2. Examples

• Requirements:
Draw flowcharts/structure charts/pseudo code and write code for
the following algorithms

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 7


2. Examples

1. Add two numbers entered by the user

Step 1:
Start
Step 2:
Declare variables num1, num2 and sum.
Step 3:
Read values num1 and num2.
Step 4:
Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 8


2. Examples

2. Find the largest number among three numbers


Step 1:
Start
Step 2:
Declare variables a,b and c.
Step 3:
Read variables a,b and c.
Step 4:
If a > b
If a > c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b > c
Display b is the largest number.
Else
Display c is the greatest number.
Step 5: Stop

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 9


2. Examples

3. Find roots of a Quadratic Equation ax2+bx+c=0


Step 1: Start
Step 2: Declare variables a, b, c, D, r1, r2, rp and ip;
Step 3: Calculate discriminant
D ← b2-4ac
Step 4: If D ≥ 0
r1 ← (-b+√D)/2a
r2 ← (-b-√D)/2a
Display r1 and r2 as roots.
Else
Calculate real part and imaginary part
rp ← -b/2a
ip ← √(-D)/2a
Display rp+j(ip) and rp-j(ip) as roots
Step 5: Stop

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 10


2. Examples

4. Find the factorial of a number


Step 1: Start
Step 2: Declare variables n, factorial and i.
Step 3: Initialize variables
factorial ← 1
i ← 1
Step 4: Read value of n
Step 5: Repeat the steps until i = n
5.1: factorial ← factorial*i
5.2: i ← i+1
Step 6: Display factorial
Step 7: Stop

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 11


2. Examples

5. Check whether a number is prime or not


Step 1: Start Step 5: Repeat the steps until i=(n/2)
Step 2: Declare variables n, i, flag. 5.1 If remainder of n÷i equals 0
Step 3: Initialize variables flag ← 0
flag ← 1 Go to step 6
i ← 2 5.2 i ← i+1
Step 4: Read n from the user. Step 6: If flag = 0
Display n is not prime
else
Display n is prime
Step 7: Stop

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 12


2. Examples

6. Find the Fibonacci series till the term less than 1000
Step 1: Start
Step 2: Declare variables first_term,second_term and temp.
Step 3: Initialize variables first_term ← 0 second_term ← 1
Step 4: Display first_term and second_term
Step 5: Repeat the steps until second_term ≤ 1000
5.1: temp ← second_term
5.2: second_term ← second_term + first_term
5.3: first_term ← temp
5.4: Display second_term
Step 6: Stop

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 13


3. Algorithm Complexity

• Complexity in algorithms refers to the amount of resources required to


solve a problem or perform a task. Two main criteria:
• Time complexity: the amount of time an algorithm takes to produce a result as
a function of the size of the input.
• Measured by calculating the iteration of loops, number of comparisons…
• For real-time systems: number of memory accesses, algebraic calculations, executed loops…
• Memory/Space complexity: the amount of memory used by an algorithm.
• Space reserved by necessary input variables
• Extra space required for the algorithm to perform

The designer must strive to develop algorithms designer


with the lowest possible time and memory complexities
⇒ More efficient and scalable program memory time
complexity complexity

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 14


3. Algorithm Complexity

• Cases in complexity
• Worst case or upper bound: 𝑂(𝑛)
• Best case or lower bound: Ω 𝑛
• Average case: Θ 𝑛
where 𝑛 is the size of input
• Example:
• Searching in an unsorted list:
linear complexity 𝑂 𝑛
• Find duplicate in an unsorted list:
quadratic complexity 𝑂 𝑛2
• Search a word in a sorted list (dictionary):
logarithmic complexity 𝑂 log 𝑛 Source: https://devopedia.org/algorithmic-complexity
• Quicksort complexity: Ω 𝑛 log 𝑛 , Θ 𝑛 log 𝑛 , 𝑂 𝑛2
𝑂(1) < 𝑂(log 𝑛) < 𝑂( 𝑛) < 𝑂(𝑛) < 𝑂(𝑛 log 𝑛) < 𝑂(𝑛2 ) < 𝑂(𝑛3 ) < 𝑂(2𝑛 ) < 𝑂(10𝑛 ) < 𝑂(𝑛!)

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 15


3. Algorithm Complexity

• Complexity of
sorting algorithms
(Source: Big-O Cheat Sheet,
2016)

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 16


4. Fundamental Algorithms | 4.1. Sorting Algorithms

4.1.1. Bubble Sort:


Suppose sorting the elements of an array in ascending order
Step 1 Step 2 Step 3 Step 4
i = 0 -3 11 2 -8 4 -3 2 -8 4 11 -3 -8 2 4 11 -3 -8 2 4 11

i = 1 -3 11 2 -8 4 -3 2 -8 4 11 -8 -3 2 4 11 -8 -3 2 4 11

i = 2 -3 2 11 -8 4 -3 -8 2 4 11 -3 -8 2 4 11

i = 3 -3 2 -8 11 4 -3 -8 2 4 11

-3 2 -8 4 11

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 17


4. Fundamental Algorithms | 4.1. Sorting Algorithms

• Bubble sort algorithm

begin BubbleSort(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort

⇒ Write the code yourself

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 18


4. Fundamental Algorithms | 4.1. Sorting Algorithms

• Bubble sort code


def BubbleSort(sorting_array):
temp = 0
for i in range(len(sorting_array)):
for j in range(len(sorting_array)-i-1):
if (sorting_array[j] > sorting_array[j+1]):
temp = sorting_array[j+1]
sorting_array[j+1] = sorting_array[j]
sorting_array[j] = temp
return sorting_array

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 19


4. Fundamental Algorithms | 4.1. Sorting Algorithms

• Bubble sort complexity


Step 1 Step 2 Step 3 Step 4
i = 0 -3 11 2 -8 4 -3 2 -8 4 11 -3 -8 2 4 11 -3 -8 2 4 11

i = 1 -3 11 2 -8 4 -3 2 -8 4 11 -8 -3 2 4 11 -8 -3 2 4 11

i = 2 -3 2 11 -8 4 -3 -8 2 4 11 -3 -8 2 4 11

i = 3 -3 2 -8 11 4 -3 -8 2 4 11

-3 2 -8 4 11
4 3 2 1
No. of
comparison (n-1) (n-2) (n-3) (n-4) …
𝑛 𝑛−1
Number of comparisons = 𝑛 − 1 + 𝑛 + 2 + ⋯ + 1 = ⇒ Complexity: 𝑂 𝑛2
2

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 20


4. Fundamental Algorithms | 4.1. Sorting Algorithms

• Bubble sort complexity:


• Time complexity:
• Worst case complexity: 𝑂 𝑛2
• Best case complexity: Ω 𝑛 , i.e., if the array is sorted, there is no need for sorting
• Average case complexity: Θ(𝑛2 )
• Space complexity: 𝑂 1 , i.e., only one extra variable for swapping
• Application: Bubble sort is used when:
• Complexity does not matter
• Short and simple code are preferred

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 21


4. Fundamental Algorithms | 4.1. Sorting Algorithms

4.1.2. Selection Sort:


Step 1 Step 2 Step 3 Step 4
0 2 2 4
i = 0 -3 11 2 -8 4 -8 11 2 -3 4 -8 -3 2 11 4 -8 -3 2 11 4

0 3 2
i = 1 -3 11 2 -8 4 -8 11 2 -3 4 -8 -3 2 11 4 -8 -3 2 4 11

3 3
i = 2 -3 11 2 -8 4 -8 11 2 -3 4 -8 -3 2 11 4

3
i = 3 -3 11 2 -8 4 -8 -3 2 11 4

-8 11 2 -3 4
Note: Red numbers are the indices of the minimum elements

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 22


4. Fundamental Algorithms | 4.1. Sorting Algorithms

• Selection sort: Algorithm

selectionSort(array, size)
repeat (size - 1) times
set the first unsorted element as the minimum
for each of the unsorted elements
if element < currentMinimum
set element as new minimum
swap minimum with first unsorted position
end selectionSort

⇒ Write the code yourself

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 23


4. Fundamental Algorithms | 4.1. Sorting Algorithms

• Selection sort: the Code


def InsertionSort(sorting_array):
temp = 0
for i in range(len(sorting_array)):
min_index = i
for j in range(i,len(sorting_array)-1):
if sorting_array[j+1] < sorting_array[min_index]:
min_index = j+1
temp = sorting_array[i]
sorting_array[i] = sorting_array[min_index]
sorting_array[min_index] = temp
return sorting_array

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 24


4. Fundamental Algorithms | 4.1. Sorting Algorithms

• Selection sort complexity:


• Time complexity:
• Worst case complexity: 𝑂 𝑛2
• Best case complexity: Ω 𝑛2 , even if the array is already sorted
• Average case complexity: Θ(𝑛2 )
• Space complexity: 𝑂 2 , i.e., two extra variables for swapping and index
• Application: Selection sort is used when:
• A small list is to be sorted
• Cost of swapping does not matter
• Checking of all elements is mandatory

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 25


4. Fundamental Algorithms | 4.1. Sorting Algorithms

4.1.3. Insertion Sort


Step 1 Step 2 Step 3 Step 4

2 -3 -8 -1 11 -3 2 -8 -1 11 -8 -3 2 -1 11 -8 -3 -1 2 11
Key Key Key Key
-3 2 2 -8 -1 11 -8 -3 2 2 -1 11 -1 -8 -3 2 2 11 11

-3 -3 2 -1 11 -8 -3 -1 2 11 -8 -3 -1 2 11
-3 2 -8 -1 11

-8 -3 2 -1 11

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 26


4. Fundamental Algorithms | 4.1. Sorting Algorithms

• Insertion sort: Algorithm


insertionSort(array)
mark first element as sorted
for each unsorted element X
'extract' the element X
for j <- lastSortedIndex down to 0
if current element j > X
move sorted element to the right by 1
break loop and insert X here
end insertionSort
⇒ Write the code yourself

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 27


4. Fundamental Algorithms | 4.1. Sorting Algorithms

• Insertion sort: code


def InsertionSort(sorting_array):
for i in range(1,len(sorting_array)):
key = sorting_array[i]
j = i-1
while j >=0 and sorting_array[j]>key:
sorting_array[j+1] = sorting_array[j]
j -= 1
sorting_array[j+1] = key
return sorting_array

⇒ Code with all for-loop yourself

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 28


4. Fundamental Algorithms | 4.1. Sorting Algorithms

• Insertion sort complexity


• Time complexity:
• Worst case complexity: 𝑂 𝑛2
• Best case complexity: Ω 𝑛 , even if the array is already sorted
• Average case complexity: Θ(𝑛2 )
• Space complexity: 𝑂 1 , i.e., one extra variable for key
• Application: Insertion sort is used when:
• A small list is to be sorted
• There are only a few elements left to be sorted

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 29


4. Fundamental Algorithms | 4.1. Sorting Algorithms

• Other sorting algorithm


• Merge sort
• Quick sort
• Counting sort
• Radix sort
• Bucket sort
• Heap sort
• Shell sort
• Students are recommended to self-study more on sorting

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 30


4. Fundamental Algorithms | 4.2. Searching Algorithms

• Why are searching algorithms important?


• Used in a wide range of problem-solving tasks
• Find an approximated root of hard-to-solve equations
• Search for the optimal operation point of a system
• Figure out the best route in a map
• Choose the best move in a game
• Optimize an industrial process by changing the
parameters of the process
• Solve the scheduling problems
• To improve the efficiency and performance of a
system There are many
• Good searching algorithm can shorten decision time different types of
• Performance is a critical criteria for real-time systems searching algorithm
Two popular algorithms: Linear Search and Binary Search

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 31


4. Fundamental Algorithms | 4.2. Searching Algorithms

• Practical example 1
A flat beam of light is bent
when going near a highly charged
Highly Electricity
sphere.
Charged Sphere
On the screen, we collected a
curve of light instead of a straight
one.
Requirement: Find the
trajectory of the line on the
screen.
Problem: Solve the equation Light Beam Source
below
2
𝑟−𝑅−∆𝑅 2 𝑟−𝑅−∆𝑅 2
− −
𝑛0 − 51.10−6 . 𝑇0 + ∆𝑇. 𝑒 𝑐 − 11.10−8 . 𝑇0 + ∆𝑇. 𝑒 𝑐 . 𝑟 − 𝑛0 . 𝑥0 = 0

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 32


4. Fundamental Algorithms | 4.2. Searching Algorithms

• Practical example 2:
Studied object: dual-motor EV with efficiency
maps for each electric motor
Problem: find the optimal operation points of
motors for the best efficiency
Energetic index in acceleration:
𝑘𝑓𝑟 1−𝑘𝑓𝑟
𝐽𝑎𝑐𝑐 = +
𝜂𝐸𝐷𝑓 𝜂𝐸𝐷𝑟

𝑘𝑓𝑟 = 𝑎𝑟𝑔𝑚𝑖𝑛 𝐽𝑎𝑐𝑐 𝑤𝑖𝑡ℎ 𝑘𝑓𝑟 ≔ 0 → 1
Energetic index in deceleration
𝐽𝑑𝑒𝑐 = 𝑘𝑓𝑟 𝜂𝐸𝐷𝐹 + 1 − 𝑘𝑓𝑟 𝜂𝐸𝐷𝑟

𝑘𝑓𝑟 = 𝑎𝑟𝑔𝑚𝑖𝑛 𝐽𝑑𝑒𝑐 𝑤𝑖𝑡ℎ 𝑘𝑓𝑟 ≔ 0 → 1

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 33


4. Fundamental Algorithms | 4.2. Searching Algorithms

• Practical example 3
Studied object: a HESS electric
vehicle
Problem: Optimal energy
management of the two sources
𝑡 2
𝐽 = ‫׬‬0 𝑓 𝑃𝑏𝑎𝑡 𝑑𝑡
Constraints:
𝑃𝑏𝑎𝑡−𝑚𝑖𝑛 ≤ 𝑃𝑏𝑎𝑡 ≤ 𝑃𝑏𝑎𝑡−𝑚𝑎𝑥
𝑈𝑆𝐶−𝑚𝑖𝑛 ≤ 𝑈𝑆𝐶 ≤ 𝑈𝑆𝐶−𝑚𝑎𝑥
𝑈𝑆𝐶−𝑓𝑖𝑛𝑎𝑙 = 𝑈𝑆𝐶−𝑖𝑛𝑖𝑡

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 34


4. Fundamental Algorithms | 4.2. Searching Algorithms

• Practical example 3 (cont.)

𝐸𝑆𝐶

𝐸𝑆𝐶_𝑚𝑎𝑥
𝐸𝑆𝐶_𝑖𝑛𝑖𝑡

𝐸𝑆𝐶_𝑚𝑖𝑛

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 35


4. Fundamental Algorithms | 4.2. Searching Algorithms

4.2.1. Linear Search


• Assume that we need to find number k = 5 in a list
𝑘=5

i = 0 2 -3 -8 5 11

𝑘≠2
i = 1 2 -3 -8 5 11
𝑘 ≠ −3
i = 2 2 -3 -8 5 11
𝑘 ≠ −8
Return i i = 3 2 -3 -8 5 11
𝑘=5

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 36


4. Fundamental Algorithms | 4.2. Searching Algorithms

• Linear Search: Algorithm and Code

LinearSearch(array, key)
for each item in the array
if item == value
return its index

def LinearSearch(searching_array, num_to_search):


for i in range(len(searching_array)):
if searching_array[i] == num_to_search:
return i
return -1

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 37


4. Fundamental Algorithms | 4.2. Searching Algorithms

4.2.2. Binary Search

Let’s play a guessing game!

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 38


4. Fundamental Algorithms | 4.2. Searching Algorithms

• Binary Search: Algorithm


do until the pointers low and high meet each other.
mid = (low + high)/2
if (x == arr[mid])
return mid
else if (x > arr[mid]) // x is on the right side
low = mid + 1
else // x is on the left side
high = mid - 1

⇒ Write the code yourself

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 39


4. Fundamental Algorithms | 4.2. Searching Algorithms

• Binary Search: Code


def BinarySearch(searching_array, number_to_search):
min_index = 0
max_index = len(searching_array)
mid = int((min_index+max_index)/2)
while searching_array[mid] != number_to_search :
if searching_array[mid] > number_to_search:
max_index = mid
else:
min_index = mid
if (max_index-min_index)==1:
mid = -1
break
else:
mid = int((min_index+max_index)/2)
return mid
EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 40
4. Fundamental Algorithms | 4.2. Searching Algorithms

• Binary Search: Complexity


• Time complexity:
• Worst case complexity: 𝑂 log 𝑛
• Best case complexity: Ω 1
• Average case complexity: Θ(log 𝑛)
• Space complexity: 𝑂 3 , i.e., three extra variables for indices
• Applications: Many

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 41


4. Fundamental Algorithms | 4.2. Searching Algorithms

• Other searching algorithms


• Sentinel Linear Search
• Meta Binary Search
• Ternary Search
• Jump Search
• Interpolation Search
• Exponential Search
• Fibonacci Search

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 42


5. Recursion | 5.1. Definition

Recursion is the process of repeating items in a self-similar way.

• Algorithmically: a way to design solutions to problems by divide-and-


conquer or decrease-and-conquer.
⇒ Reduce a problem to small and simpler versions of the same problem

• Semantically: a programming technique where a function calls itself


• In programming, the goal is to not have infinite recursion. To do that:
• The program must have 1 or more base cases that are easy to solve
• It must solve the same problem on some other inputs with the goal of simplifying
the larger problem input.

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 43


5. Recursion | 5.2. Iteration algorithm so far

• Looping structures using while and for loops lead to the iterative
algorithm
• The value of computation of the program can be captured in a set of
state variables which are updated on each iteration through loops
• Example of “Multiplication” using iteration method
• The multiplication of a and b (axb) is equivalent to add a to itself b times

Step 1: Declare mul = 0


to store value of computation def mul_ab(a, b) :
mul = 0
Step 2: Add a to mul
for i in range(1, b+1):
Step 3: Loop b times using counter i mul += a
to capture state variable return mul
Step 4: Return mul

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 44


5. Recursion | 5.3. Recursive Technique

5.3.1. Multiplication Recursive Solution


𝑎 ×𝑏 = 0 + 𝑎 +𝑎 + 𝑎 +⋯+ 𝑎 def mul_recusive(a, b) :
𝑏 𝑡𝑖𝑚𝑒𝑠 if b == 1 : Base case
= 𝑎 + 𝑎 + 𝑎 + 𝑎 + ⋯+ 𝑎 return a
𝑏−1 𝑡𝑖𝑚𝑒𝑠 else :
return a + mul_recusive(a, b-1)
= 2𝑎 + 𝑎 + 𝑎 + 𝑎 + ⋯ + 𝑎
𝑏−2 𝑡𝑖𝑚𝑒𝑠
⇒ Generalization: Smaller version
𝑎×𝑏 =𝑎+𝑎× 𝑏−1
or mul(a,b) = a + mul(a,b-1) Try to recognize
the pattern!
Base case: the case that can be solved directly
b = 1 → axb = a

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 45


5. Recursion | 5.3. Recursive Technique

5.3.2. Factorial
𝑛! = 1 × 2 × 3 × ⋯ × (𝑛 − 1) × 𝑛
• The pattern/smaller version?
𝑛! = 𝑛 × 𝑛 − 1 !
or facto(n)=n*facto(n-1)
• The base case?
if n=1 → n! = 1
• The code? def facto(n) :
if n == 1 :
return 1
else :
return n*facto(n-1)

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 46


5. Recursion | 5.3. Recursive Technique

• What happens in the recursion of factorial


for example, n = 4: print(facto(4))
Global Scope facto Scope facto Scope facto Scope facto Scope
call with n=4 call with n=3 call with n=2 call with n=1

facto n n n n
some
4 3 2 1
code

print(facto(4)) return 4*facto(3) return 3*facto(2) return 2*facto(1) return facto(1)

return 4*6 return 4*6 return 3*2 return 2*1 return 1


print(24) Base case

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 47


5. Recursion | 5.3. Recursive Technique

5.3.3. Fibonacci Sequence


𝐹 𝑛 = 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + ⋯
𝐹(0) 𝐹 1 𝐹(2) 𝐹(3) 𝐹(4) 𝐹(5) 𝐹(6) 𝐹(7)
0 1 1 2 3 5 8 13

• The pattern/smaller version?


𝐹 𝑛 = 𝐹 𝑛 − 1 + 𝐹(𝑛 − 2)
or Fibo(n) = Fibo(n-1) + Fibo(n-2)
• The base case? def Fibo(n):
if n == 0:
if n = 0 → F(0) = 0 return 0
elseif n = 1 → F(1)=1 elif n == 1:
return 1
• The code? else:
return Fibo(n-2) + Fibo(n-1)
EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 48
5. Recursion | 5.3. Recursive Technique

A B C
5.3.4. Well-known the Tower of Hanoi – Exercise
• The puzzle invented by Édouard Lucas in 1883
• Objective: move all n disks from rod A to rod C
• Only one disk can be moved at a time
• The moving disk can be placed on other disks at another
rod or to an empty rod
• No disk is allowed to be put on top of a smaller disk
• So, find the pattern (smaller version), the base case
and then code

EE3491 - Programming Techniques | Control and Automation Engineering – SEEE, HUST 49


END OF CHAPTER 3
ALGORITHMS – PART I

50

You might also like