0% found this document useful (0 votes)
4 views69 pages

PT - Chapter 1 - Functions and Processing Techniques

This document is a lecture outline on programming techniques focusing on functions and processing techniques. It covers concepts such as the definition and structure of functions, how to call them, variable scope, default parameters, lambda expressions, and recursive functions. The document aims to equip students with the knowledge to build and utilize functions effectively in programming.

Uploaded by

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

PT - Chapter 1 - Functions and Processing Techniques

This document is a lecture outline on programming techniques focusing on functions and processing techniques. It covers concepts such as the definition and structure of functions, how to call them, variable scope, default parameters, lambda expressions, and recursive functions. The document aims to equip students with the knowledge to build and utilize functions effectively in programming.

Uploaded by

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

VIETNAM NATIONAL UNIVERSITY HO CHI MINH CITY

UNIVERSITY OF ECONOMICS AND LAW


Programming Techniques
Chapter I
FUNCTIONS AND PROCESSING TECHNIQUES

Lecturer:
Trần Duy Thanh, PhD.
Email: [email protected]
Blog: https://tranduythanh.com
Objectives
 After completing this chapter, students understand the concept and
meaning of functions as well as the general structure of functions.
 Students will be able to build and call functions in many different ways
 Understand and explain the mechanism of operation of functions
 Understand the rules about the scope of influence of variables in
functions
 Build functions with default parameters, functions that return multiple
results as well as functions according to Lambda expressions
 Understand and build Recursive functions
 Create documents for functions
Faculty of Information
2
Systems
Contents
• 1.1. Concept and meaning of function
• 1.2. General structure of function
• 1.3. How to call function
• 1.4. Function operation mechanism
• 1.5. Scope of influence of variables in function
• 1.6. Building function with default parameters
• 1.7. Building function by Lambda Expression
• 1.8. Function returns multiple results
• 1.9. Recursive function
• 1.10. Creating documents for function.
Faculty of Information
3
Systems
1.1. Concept and meaning of function

A function is a block of code that performs a complete task (module), and is called many
times at many locations in the program.

A function is also called a subroutine

Classification of functions:
 Library function: must import library before using function (from … import)
 User-defined function.

Faculty of Information
4
Systems
1.1. Concept and meaning of function

Examples of library functions, User-defined function functions


Example 1: Library function: from decimal import *
x = 6.6789
y = Decimal(x)
print(type(x))
print(type(y))

Example 2: User-defined function:


def Sum(x, y):
return x + y

a=8
b=9
c = Sum(a, b)
print(f"Sum = {c}")
Faculty of Information
5
Systems
1.2. General structure of the function

 Python has the following general structure when declaring a Function:

 Use the def keyword to define a function, functions can have arguments or
not. They can return a result or not.

Faculty of Information
6
Systems
1.2. General structure of the function

Function definition example


Function to print greeting:
def sayWelcome():
print("Welcome To
UEL")
Function to check if a number is even:
def isEven(x):
if x % 2 == 0:
return True
return False
Division function:
def division(a, b):
return a / b

Faculty of Information
7
Systems
1.3. Invoking a function

When calling a function, you need to fully declare all arguments, if any.
Calling a function with no return value:
FunctionName([parameter])  sayWelcome()
Call the function that returns:
result = FunctionName([parameter])
 b = isEven(8)
 x = division(9, 2)
 or x=division(a=2, n=9)

Faculty of Information
8
Systems
1.3. Invoking a function
 Example: Write a function to solve a first degree equation.

We can call it as follows: result=firstDegree(3,5)


 Example: Write a function to print data to the monitor

def printData(data):
print(data)
We can call: printData("Tran Duy Thanh")
Faculty of Information
9
Systems
1.4. Function operation mechanism
 Functions in Python, as well as in other programming languages, work
on the LIFO (LAST IN FIRST OUT) Principle.
 For example, we have the following code:

 How does it happen under LIFO?

Faculty of Information
10
Systems
1.4. Function operation mechanism
 Illustration of the principle of operation when calling a function

Faculty of Information
11
Systems
1.5. Scope of influence of variables in function
 All variables declared in a function only have scope within the function,
these variables are called local variables. When exiting the function,
these variables cannot be accessed.
 Example 1: Global variable

Local variable

Global variable
 According to you, after running the 6 command lines above, what is the value of g
output to the screen?

Faculty of Information
12
Systems
1.5. Scope of influence of variables in function
 Example 2:

 According to you, after running the 7 command lines above, what is the value of g
output to the screen?
 The global keyword allows us to reference and use the Global variable.

Faculty of Information
13
Systems
1.5. Scope of influence of variables in function
 Example 3:

 g line 3 gets an error, because g inside the function cannot access g


outside (declared on line 1)

Faculty of Information
14
Systems
1.5. Scope of influence of variables in function
 What is the result of x after executing the commands below?
x=8 x=8 x=8
def def def
increment(): increment(): increment():
x=6 global x x=x+1
x=x+1 x=6 increment()
?
increment() ? x=x+1 print(x)
print(x) increment() ?
print(x)

Faculty of Information
15
Systems
1.6. Building function with default parameters
Consider the following print function:

Default parameters are parameters that are assigned a value when declaring a
function. They will automatically take this value if we do not pass a value to the
parameter when calling the function.

Faculty of Information
16
Systems
1.6. Building function with default parameters
Example:
def lastItem(m, n=0):
last = 0
for i in range(1, m+n, 1):
last = i n will take default value
return last =0

x = lastItem(8)
print("x = {0}".format(x))
y = lastItem(8, 2)
print(f"y = {y}")

Faculty of Information
17
Systems
1.7. Building function by Lambda Expression

 Python supports anonymous function declaration via Lambda


expression:
parameter expressio
lambda :
list n
 lambda is a keyword
 paramaterlist: a set of parameters that we want to define
 expression: a simple expression in Python (no complex input)

Faculty of Information
18
Systems
1.7. Building function by Lambda Expression

 For example, we define a function


 We see that argument 1 is some function f
 From this handle we can call arbitrary transactions:
ret1=handle(lambda x:x%2==0,7)
ret2=handle(lambda x:x%2!=0,7)
 Before the colon is the keyword lambda, after it is the number of
variables declared in handle (counted after the letter f). That is, if we
handle(f,x,y) then write lambda x, y :

Faculty of Information
19
Systems
1.7. Building function by Lambda Expression

 Because lambda expression does


not accept complex writing, so if
we want complex, we should
define independent functions
and pass them to Lamba
expression.
 For example: Here we have 4
functions, in which isEven, isOdd,
isPrimeNumber will be called
into handle

Faculty of Information
20
Systems
1.7. Building function by Lambda Expression

Some test cases:


ret1=handle(isEven,6)
print(ret1)
ret2=handle(lambda x:isEven(x),6)
True
print(ret2)
True
ret3=handle(isOdd,6)
False
print(ret3)
True
ret4=handle(lambda x: isOdd(x),7)
True
print(ret4)
False
ret5=handle(isPrimeNumber,5)
print(ret5)
ret6=handle(lambda x:isPrimeNumber(x),9)
print(ret6)

Faculty of Information
21
Systems
1.8. Function returns multiple results

Python, like C# (new version), supports writing functions that return


multiple results, this feature is very useful.
# A Python program to return multiple
# values from a method using tuple

# This function returns a tuple


def fun():
str = "UEL"
year = 25
return str, year # Return tuple, we could also
# write (str, year)

# Driver code to test above method


v1, v2 = fun() # Assign returned tuple
print(v1)
print(v2)
Faculty of Information
22
Systems
1.9. Recursive function

• A function is called recursive if a statement in the body of the function calls


the function itself. Recursion helps solve problems in a natural way.
• Recursion must determine the stopping point. If it is not determined
correctly, the problem will be wrong and may loop endlessly (Stack
Overhead).
• And Recursion must determine the rule of running the program so that each
time it is repeated, the scale of the problem is narrowed towards the
stopping point.
• Normally, we should try to solve recursive problems with loops, only when
we cannot solve them with loops should we think about recursion.
Therefore, we should think about loops to find a way to solve recursion.

Faculty of Information
23
Systems
1.9. Recursive function
 Example: Definition of the factorial of a positive integer n is as follows:
• 5!=5*4!
• 4!=4*3!
That is, if we know (n-1) factorials, we can calculate n factorials, because n!
=n*(n-1)!

 Rewrite the conditional recursive equation:

The stopping point is when n=0, the rule is if


we know (n-1)! then we can calculate n!,
because n!=n*(n-1)! And each time we run, the
scale of n decreases to 0 (the stopping point)
Faculty of Information
24
Systems
1.9. Recursive function

Faculty of Information
25
Systems
1.9. Recursive function

Faculty of Information
26
Systems
1.9. Recursive function
The operating mechanism of recursion follows LIFO (Last In First Out), also
known as the Stack mechanism.

Faculty of Information
27
Systems
1.9. Recursive function
 Recursion is classified into 6 types:
 LINEAR RECURSION
 TAIL RECURSION
 BINARY RECURSION
 EXPONENTIAL RECURSION
 NESTED RECURSION
 MUTUAL RECURSION

Faculty of Information
28
Systems
1.9. Recursive function
 LINEAR RECURSION
Linear recursion is the case where a function only calls itself once. Similar
to the factorial problem:

Faculty of Information
29
Systems
1.9. Recursive function
 LINEAR RECURSION
Write a recursive function to convert base 10 to base 2
13 2
Let n=13 be a natural number with base 10.
12 6 2 To convert it to binary recursively, we have:
3 2 - Stop point n=0
1 6
- The rule is to take the remainder of n with
2 1 2
0 2, each time taking the remainder, repeat
1 0 0 n=n/2 until n=0
1 - The scale of n gradually decreases to 0
(stop point)
- When calculating the result, output it
1310=11012 backwards (representation of LIFO)

Faculty of Information
30
Systems
1.9. Recursive function
 LINEAR RECURSION
Note, if we observe with the naked eye, most of us will get
Write a recursive function to the following error:
convert base 10 to base 2 The order of execution of the commands of the H10ToH2
function is:
- Line 1
- Line 2
- Line 3
- Line 4
- Line 5
- Line 6
 If we understand the above order, it is wrong, because it
is related to recursion, it will operate in STACK (LIFO)
form. When the recursive call to Line 5 ends, it will never
execute Line 6 immediately. It must process the Stack first,
Faculty of Information
31
then Line 6.
Systems
1.9. Recursive function
 LINEAR RECURSION
Line 5 recursively calls H10ToH2(n), At this time, the
program will save to Stack, saving 2 important data:
+ The command directive immediately after the
recursive call (i.e. the command directive on line 6)
+ The value of the Local variables (Local variables are
variables declared in the function content and in the
function's arguments). In this case, the remainder
variable and the n variable.
-When the recursion is finished (at the stopping point),
the program will check if the STACK is still empty or
not. If the STACK is not empty, it will take the data that
we saved for further processing. Take according to the
LIFO principle.
Faculty of Information
32
Systems
1.9. Recursive function H10toH2(13)H(13)
n=3, remainder=0
1.If n>0 13>0true
remainder=13%2=1 n=6, remainder=1
n=n/2=13/2=6
Stack
Call H(6)Push Stack
2. If 6>0true
remainder =6%2=0, n=n/2=6/2=3 n=1, remainder=1
Call H(3)Push Stack n=3, remainder=0
3.If 3>0true
remainder =3%2=1, n=n/2=1 n=6, remainder=1
Call H(1)Push Stack Stack

4.If 1>0true n=0, remainder=1


n=6, remainder =1 remainder =1%2=1
Stack n=n/2=1/2=0 n=1, remainder=1
Call H(0)Push Stack
n=3, remainder=0
5.If 0>0FalseEnd Recursive
Faculty of Information
33
then call Stack n=6, remainder=1
Systems
1.9. Recursive function
At the end of the recursion, the program will call Stack in LIFO order and return the
instruction in line 6.
= 1
0, r
m print 1
n= = 1
r m print 1
n=1, rm=1 1, 0 print 0
n= =
, rm
n=3, rm=0 n=3, rm=0 = 3
n
n=6, rm=1 n=6, rm=1 n=6, rm=1
Stack Stack Stack

print 1
Results output to screen: 1101
= 1
,r m
= 6
n
Faculty of Information
34
Systems Stack Stack
1.9. Recursive function
 TAIL RECURSION
Tail recursion is a special case of linear recursion, it has the form similar to the
following:

• m=25, n=5
• Line 10: GCD(m,n)GCD(25,5)
• Line 2: Check m<n 25<5False
• Line 4: r=m%n=25%5=0
• Line 5: Check r==0?Truereturn nreturn 5
• Line 11: Print GCD(25,5)=5

Faculty of Information
35
Systems
1.9. Recursive function
 TAIL RECURSION
Tail recursion is a special case of linear recursion, it has the form similar to the
following:
• m=5, n=25
• Line 10: GCD(m,n)GCD(5,25)
• Line 2: Check m<n 5<25True
• Line 3: return GCD(n,m)return GCD(25,5)
• Line 2: Check m<n 25<5False
• Line 4: r=m%n=25%5=0
• Line 5: Check r==0?Truereturn nreturn 5
• Line 11: Print GCD(5,25)=5

Faculty of Information
36
Systems
1.9. Recursive function
 TAIL RECURSION
Tail recursion is a special case of linear recursion, it has the form similar to the
following:
• m=7, n=3
• Line 10: GCD(m,n)GCD(7,3)
• Line 2: Check m<n 7<3False
• Line 4: r=m%n=7%3=1
• Line 5: Check r==0?False
• Line 7: return GCD(n,r)return GCD(3,1)
• Line 2: Check m<n 3<1False
• Line 4: r=m%n=3%1=0
• Line 5: Check r==0?Truereturn nreturn 1
• Line 11: Print GCD(7,3)=1
Faculty of Information
37
Systems
1.9. Recursive function
 BINARY RECURSION
Binary recursion is a form of recursion that calls itself twice, example Fibonacci
numbers: 1123581321345589… Fib(6)

def Fib(n):
if n<=2: Fib(5)
Fib(4)

return 1
return Fib(n-1)+Fib(n-2) Fib(2)
Fib(3)
n=6 Fib(4) Fib(3)
1
f=Fib(n)
print(f"Fib({n})={f}")
Fib(1)
Fib(2)
Fib(2) Fib(1)
Fib(3) Fib(2) 1
1
1 1
1

Fib(2) Fib(1)

1
Fib(6)8
1
Faculty of Information
38
Systems
1.9. Recursive function
 EXPONENTIAL RECURSION
The type that is both loop and recursive is similar (attention that the
example below is not a sorting algorithm, just an illustration of
exponential recursion):

Complexity is usually O(an)


Faculty of Information
39
Systems
1.9. Recursive function
arr=[10,2,5]
print_permutations(arr,0);p(arr,0)
Print arr10 2 5
For:
1. j=i+1=1j<len(arr) 1<3truebody:
if arr[i] > arr[j] arr[0]>arr[1]10>2true:
swap i and jarr=[2,10,5]
line 8: call recursion p(arr,1)
Print arr2 10 5
For : i=0, j=1
1. j=i+1= 22<3truebody: Stack
if(arr[i] >arr[j] arr[1]>arr[2]10>5true:
Swap i and jarr=[2,5,10] i=1, j=2
line 8: Call recursion P(arr,2)
i=0, j=1
Faculty of Information
Systems
40
Stack
1.9. Recursive function
P(arr,2) i=1, j=2

Print arr2 5 10 i=0, j=1


for: Stack
1. j=i+1=2+1=3, 3<3false
End for, end RecursionCall Stack:
Call: i=1, j=2
i=0, j=1
2. j++j=2+1=3, 3<3false
 End for, end RecursionCall Stack: Stack
Call i=0, j=1
2. j++j=1+1=2, 2<3truebody:
if arr[0] >arr[2]  2 > 10false
line 8: Call recursion P(arr, 1)
Stack
Faculty of Information
41
Systems
1.9. Recursive function

line 8: call recursion P(arr, 1)


i=0, j=2
Print arr2 5 10
For: Stack
1. j=i+1=2, 2<3truebody:
if arr[i] > arr[j] arr[1] >arr[2] 5 >10false
line 8: call Recursion p(arr, 2) i=1, j=2
Print arr2 5 10
i=0, j=2
for:
1. j = i+1=2+1=3, 3<3false Stack
End for, end RecursionCall Stack:
Call i=1, j=2

j++j=3, 3<3false i=0, j=2

Faculty of Information
Call Stack Stack
42
Systems
1.9. Recursive function

Call Stack i=0, j=2

j++j=3 ,3<3false
End For, End recursion and Stack
Stack empty
End algorithms
End Program. In total, we have the
following number of times output to the
screen:

Faculty of Information
43
Systems
1.9. Recursive function
 NESTED RECURSION
It is a recursive type that recursively calls the argument of the function,
similar to:

Faculty of Information
44
Systems
1.9. Recursive function
 NESTED RECURSION a=ackerman(2,1)=A(2,1)
A(1,A(2,0))
A(1,A(1,1))
A(1,A(0,A(1,0)))
A(1,A(0,A(0,1)))
A(1,A(0,2))
A(1,3)
A(0,A(1,2))
A(0,A(0,A(1,1)))
A(0,A(0,A(0,A(1,0))))
A(0,A(0,A(0,A(0,1)))))
A(0,A(0,A(0,2)))
A(0,A(0,3))
A(0,4)
5 At the end of the recursion, we have
Faculty of Information
a=5
45
Systems
1.9. Recursive function
 MUTUAL RECURSION
This type of recursion does not call itself directly, but calls another
function, which in turn calls it again, similarly:

Faculty of Information
46
Systems
1.9. Recursive function
result=isEven(9)
return isOdd(8)=
!isEven(8)
!isOdd(7)
!!isEven(7)
!!isOdd(6)
!!!isEven(6)
!!!isOdd(5)
!!!!isEven(5)
!!!!isOdd(4)
!!!!!isEven(4)
!!!!!isOdd(3)
!!!!!!isEven(3)
!!!!!!isOdd(2)
!!!!!!!isEven(2)
!!!!!!!isOdd(1)
!!!!!!!!isEven(1)
!!!!!!!!isOdd(0)
Faculty of Information
47 !!!!!!!!!isEven(0) false
Systems
1.9. Recursive function– Hanoi Tower

 Advanced task: Write an algorithm and illustrate each step of the recursive
process of the Tower of Hanoi problem, the rules of the game are described:
The game consists of a set of discs of different sizes, with
holes in the middle, placed across three pegs. The puzzle
begins by arranging the discs in order of size on a peg so that
the smallest disc is on top, thus creating a cone shape. The
object of the game is to move all the discs to another peg,
following the following rules:
 Only 3 columns.
 Only the top disk can be moved (the middle disk cannot be
moved).
 A disk can only be placed on top of a larger disk (the two
disks do not have to be adjacent in size, i.e. the smallest
disk can be on top of the largest disk).
Faculty of Information
48
Systems
1.9. Recursive function– Hanoi Tower

Need to move N disks from column A(Source) to


column C(Destination), with B(Auxiliary) as a
temporary column.
Recursive ideas:
• If we know how to move N-1 disks from column A to
column B  we move Disk N from column A to
column C  then move N-1 disks from column B to
column C.
• The algorithm is no longer recursive when there is
only 1 Disk, because now we move directly from
column A to column C.
Exact complexity: 2n-1
Faculty of Information
49
Systems
1.9. Recursive function– Hanoi Tower

If column A has only 1 disc

A B C
Source Auxiliary Destination

Faculty of Information
50
Systems
1.9. Recursive function– Hanoi Tower

If column A has only 2 discs

A C
B
Source Destination
Auxiliary

Faculty of Information
51
Systems
1.9. Recursive function– Hanoi Tower

If column A has 3 discs

A B C
Source Auxiliary Destination

Faculty of Information
52
Systems
1.9. Recursive function– Hanoi Tower
 Write Hanoi Tower algorithm and test with 3 disks:

Move A=>C
Move A=>B
Move C=>B
Move A=>C
Move B=>A
Move B=>C
Move A=>C

 The following Slides demonstrate and explain in detail how recursion works
for Hanoi Tower.

Faculty of Information
53
Systems
1.9. Recursive function– Hanoi Tower Explain each step of running according to
LIFO mechanism when n=3
Move 3 discs from column A
0move(3, 'A', 'B', 'C');
to column C, with column B
n=3,
as the auxiliary column: 1 n=3, A='A', B='B', C='C' A='A'
B='B'
0 move(3, 'A', 'B', C='C'
4 move(n - 1, A, C, B);
'C'); When calling stack
def move(n,A,B,C):
1
move(2, 'A', 'C', 'B'); recursively, the
if n==1:
2 instruction from
number 5 and the
n=2,
print(f"Move
3 {A}=>{C}") values ​of local
variables will be A='A'
else: put on the Stack. B='C'
C='B'
move(n-1,A,C,B)
4 1 n=2, A='A', B='C', C='B'
n=3,
print(f"Move
5 {A}=>{C}") A='A'
move(n-1,B,A,C)
6
4 move(n - 1, A, C, B); B='B'
C='C'
move(1, 'A', 'B', 'C');
Faculty of Information
stack
54
Systems
1.9. Recursive function– Hanoi Tower

Move 3 discs from column A move(1, 'A', 'B', 'C');


n=2,
to column C, with column B A='A'
as the auxiliary column: 1 n=1, A='A', B='B', C='C' B='C'
C='B'
0 move(3, 'A', 'B', 3 Move 1 disk from A ==> C
n=3,
'C'); A='A'
def move(n,A,B,C):
1 Move 1 disk from'A' ==> 'C'
B='B'
When command 3 is finished, the
if n==1:
2
recursion ends, and the system calls C='C'
Stack (gets the top). At this point,
print(f"Move
3 {A}=>{C}") the command instruction starts
stack

else: from command number 5.


5 Move 1 disk from A ==> C
move(n-1,A,C,B)
4
n=3,
print(f"Move
5 {A}=>{C}") Move 1 disk from 'A' ==> 'B' A='A'
B='B'
move(n-1,B,A,C)
6 6 move(n - 1, B, A, C) C='C'
stack
move(1, 'C', 'A', 'B');
Faculty of Information
55
Systems
1.9. Recursive function– Hanoi Tower

Move 3 discs from column A move(1, 'C', 'A', 'B');


to column C, with column B n=3,
A='A'
as the auxiliary column: 1 n=1, A='C', B='A', C='B' B='B'
C='C'
0 move(3, 'A', 'B', 3 Move 1 Disk from A ==> C
stack
'C');
def move(n,A,B,C):
1 Move 1 disk from 'C' ==> 'B'
When command 3 is finished, the
if n==1:
2
recursion ends, and the system calls
print(f"Move
3 {A}=>{C}") Stack. At this point, the command
instruction starts from command
else: number 5.
5 Move 1 disk from A ==> C
move(n-1,A,C,B)
4

print(f"Move
5 {A}=>{C}") Move 1 disk from'A' ==> 'C'
move(n-1,B,A,C)
6 6 move(n - 1, B, A, C)
stack
move(2, 'B', 'A', 'C');
Faculty of Information
56
Systems
1.9. Recursive function– Hanoi Tower

Move 3 discs from column A move(2, 'B', 'A', 'C');


to column C, with column B
as the auxiliary column: 1 n=2, A='B', B='A', C='C' n=2,
A='B'
0 move(3, 'A', 'B', 4 move(n - 1, A, C, B);
B='A'
C='C'
'C');
def move(n,A,B,C):
1
move(1, 'B', 'C', 'A'); stack
if n==1:
2 When calling recursively,
the instruction from
print(f"Move
3 {A}=>{C}") number 5 and the values ​of
local variables will be put
else: on the Stack.
move(n-1,A,C,B)
4
1 n=1, A='B', B='C', C='A'
print(f"Move
5 {A}=>{C}")
3 Move 1 disk from A ==> C
move(n-1,B,A,C)
6

Move 1 disk from 'B' ==> 'A'


Faculty of Information
57
Systems
1.9. Recursive function– Hanoi Tower
When command 3 is finished, the
Move 3 discs from column A recursion ends, and the system calls
Stack. At this point, the command n=2,
to column C, with column B instruction starts from command A='B'
as the auxiliary column: number 5. B='A'
5 Move 1 disk from A ==> C C='C'
0 move(3, 'A', 'B',
stack
'C');  Move 1 disk from 'B' ==> 'C'
def move(n,A,B,C):
1

if n==1:
2 6 move(n - 1, B, A, C)

print(f"Move
3 {A}=>{C}") move(1, 'A', 'B', 'C');
else:
1 n=1, A='A', B='B', C='C'
move(n-1,A,C,B)
4

print(f"Move
5 {A}=>{C}")
3 Move 1 disk from A ==> C
move(n-1,B,A,C)
6
 Move 1 disk from 'A' ==> 'C' stack
Stack Empty+ n=1 end of the entire recursive algorithm.
Faculty of Information
58
Systems
1.9. Recursive function– Hanoi Tower

A B C
Time 4: 'A' ==> 'C'
A B C

A B C A B C
Time 1: 'A' ==> 'C' Time 5:'B' ==> 'A'

A B C A B C
Time 2: 'A' ==> 'B' Time 6: 'B' ==> 'C'

A B C A B C
Time 3: 'C' ==> 'B' Time 7:‘A' ==> ‘C'
Faculty of Information
59
Systems
1.9. Recursive function– Hanoi Tower

If column A has 4 discs


(Students do it themselves)

A B C
Source Auxiliary Destination

Faculty of Information
60
Systems
1.10. Creating documents for function

 Python supports us to add documentation to functions, which is very


convenient for partners to use the functions we create. Based on these
documents, Partners can easily know how to use them.
 We can use 3 double quotes or 3 single quotes to write documentation
for the function. However, according to experience, you should use 3
double quotes.
 Attention (documentation) must be written in the first lines when
declaring the function

Faculty of Information
61
Systems
1.10. Creating documents for function
For example, we create a file
DocumentFunction.py
There are 2 functions
firstDegreeEquation and
quadraticEquation

https://tranduythanh.com/pt/DocumentFunction.py

Faculty of Information
62
Systems
1.10. Creating documents for function

We run the command line to see how to get documentation for the above
functions. We go to the tools menu/select Python Console…

Faculty of Information
63
Systems
1.10. Creating documents for function

We run the command line to see how to get documentation for the above
functions. We go to the tools menu/select Python Console…

from DocumentFunction import *


Faculty of Information
64
Systems
1.10. Creating documents for function
To see the documentation of a function, type: help(function name)

Faculty of Information
65
Systems
1.10. Creating documents for function
To see the documentation of a function, type: help(function name)

Faculty of Information
66
Systems
Reviews

• Question 1: Describe the general syntax of Functions, explain in detail the


mechanism of operation of the function, give illustrative examples.
• Question 2: Describe the scope of influence of variables in functions
• Question 3: Describe building and calling a function with default parameters
• Question 4: Describe Lambda Expression technique
• Question 5: Describe declaring and use functions that return multiple values.
• Question 6: Applying binary recursion to write functions ,
• Question 7: Describe how to write documentation for a function
Faculty of Information
67
Systems
Next Lesson

 In the next lesson we will learn Chapter 2, data structures in Python:


Strings, arrays, sets (List, Tuple, Set, Dictionary)

Faculty of Information
68
Systems
VIETNAM NATIONAL UNIVERSITY HO CHI MINH CITY
UNIVERSITY OF ECONOMICS AND LAW

THANK YOU!

You might also like