PT - Chapter 1 - Functions and Processing Techniques
PT - Chapter 1 - 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.
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
a=8
b=9
c = Sum(a, b)
print(f"Sum = {c}")
Faculty of Information
5
Systems
1.2. General structure of the 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
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.
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:
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:
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
Faculty of Information
18
Systems
1.7. Building function by Lambda Expression
Faculty of Information
19
Systems
1.7. Building function by Lambda Expression
Faculty of Information
20
Systems
1.7. Building function by Lambda Expression
Faculty of Information
21
Systems
1.8. Function returns multiple results
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)!
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>0true
remainder=13%2=1 n=6, remainder=1
n=n/2=13/2=6
Stack
Call H(6)Push Stack
2. If 6>0true
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>0true
remainder =3%2=1, n=n/2=1 n=6, remainder=1
Call H(1)Push 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<5False
• Line 4: r=m%n=25%5=0
• Line 5: Check r==0?Truereturn nreturn 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<25True
• Line 3: return GCD(n,m)return GCD(25,5)
• Line 2: Check m<n 25<5False
• Line 4: r=m%n=25%5=0
• Line 5: Check r==0?Truereturn nreturn 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<3False
• 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<1False
• Line 4: r=m%n=3%1=0
• Line 5: Check r==0?Truereturn nreturn 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: 1123581321345589… 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):
Faculty of Information
Call Stack Stack
42
Systems
1.9. Recursive function
j++j=3 ,3<3false
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
A B C
Source Auxiliary Destination
Faculty of Information
50
Systems
1.9. Recursive function– Hanoi Tower
A C
B
Source Destination
Auxiliary
Faculty of Information
51
Systems
1.9. Recursive function– Hanoi Tower
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
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
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
A B C
Source Auxiliary Destination
Faculty of Information
60
Systems
1.10. Creating documents for 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…
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
Faculty of Information
68
Systems
VIETNAM NATIONAL UNIVERSITY HO CHI MINH CITY
UNIVERSITY OF ECONOMICS AND LAW
THANK YOU!