Slides Combined
Slides Combined
Fundamentals
1. Introduction
1
Software Development
2
Representation
• Numbers
• Strings
• Arrays
• Multi-dimensional Arrays
3
Algorithms
get a number
https://en.wikipedia.org/wiki/Flowchart
Algorithm Vs Program
Algorithm Program
• Ideas • The final code on a
machine
get a number
• Requires
Data Structures
o Representation of the problem
Reasoning ability
o Algorithms
9
An overview of
Why are we learning Python?
• Example: Paypal
ASF XML Serialization
o C++
• 1580 lines
o Python
• 130 lines
Python Program without Learning
a = 1
b = 2
c = a + b
if c < 0:
print('Yes')
else:
print('No')
Intuitive!
Pseudo Code to Program
Algorithm Program
get a number
IDE:
o Integrated development environment
• Edit, run and debug
• Other tools
Jupyter notebook
PyCharm
Spyder
Visual Studio Code, etc.
A Screenshot of IDLE
Console
Editor
- Input
and Your
- output
program
Let’s go for
some demo
You can
Output of your
Representation
Integers, Floats, Boolean,
Numbers
etc.
Strings, Tuples
Sequences
Built-in Types*
Lists
• Floats: float
Stores real numbers as binary fractions
64-bit double precision*
• Self Exercise:
Convert the decimal numbers 0.375 and 0.1 to binary. What do you learn from the
conversion?
https://en.wikipedia.org/wiki/Double-precision_floating-point_format
22
https://docs.python.org/3/tutorial/floatingpoint.html#tut-fp-issues
Boolean Type
23
Identifiers
• Rules
First character should be an alphabet or underscore ( _ )
Other characters can be numbers and underscore
Special characters not allowed
Names are case sensitive assignment operation
24
Multiple Assignments
Python is Dynamically Typed
• No need to declare
object type
• Interpreter
automatically
recognizes the type
26
• Keywords cannot be used as identifiers
27
builtins
28
Keyword Types
Type Example
Value Keywords True, False, None
Operator Keywords and, or, not, in, is
Control Flow Keywords if, else, elif
Iteration Keywords for, while, break, continue, else
Structure Keywords def, class, with, as, pass, lambda
Returning Keywords return, yield
Import Keywords import, from, as
Exception-handling Keywords try, except, raise, finally, else, assert
Asynchronous Programming async, await
Keywords
Variable Handling Keywords del, global, nonlocal
29
Operators
• Arithmetic Operators
• Logical Operators
• Equality Operators
• Comparison Operators
30
Arithmetic Operators
31
Mixed mode arithmetic
32
Comparison Operators
33
is operator
34
is operator
• Binary operator
Returns true if identity of both operands is same
• What is identity?
Namespace objects
500
x
500
y
35
Keyword is
• Binary operator
Returns true if identity of both operands is same
• What is identity?
Namespace
500
x
36
Logical/Boolean Operators
https://en.wikipedia.org/wiki/Short-circuit_evaluation
Demo in IDLE 37
and Operator
38
or Operator
39
not Operator
40
Augmented Assignment Operators
Operation Description
x += y x=x+y
x *= y x=x*y
x /= y x=x/y
x // = y x = x //y
x ** = y x = x**y
41
Expressions
• Expressions
A piece of syntax evaluated to some value
Combination of operators and operands
o Value is an expression
o Variable is an expression
o Combination of values, variables and operators is also an expression
42
Standard IO: Input
• Input
• Type Casting
Conversion of one type to other
Example:
43
Standard IO: Output
44
Precedence
Operator Description
() Parenthesis
** Exponentiation
in, not, <, <=, >, >=, ==, != Membership, comparison and identity tests
or Boolean OR
45
Precedence
(4-5) * 3 – 7 % 4 ** 2 / 3 Operator
()
-1 * 3 - 7 % 4 ** 2 / 3 **
+x, -x
-1 * 3 - 7 % 16 / 3 *, /, //, %
+, -
-3 - 7 % 16 / 3 in, not, <, <=, >, >=, ==, !=
not x
-3 - 7 / 3 and
or
-3 - 2.333334
46
Strings
• Example Strings
It is IT5001
It’s IT5001
C:\new\IT5001
47
Strings
• Single quotes:
Example
o It is IT5001
o “It is IT5001,” said Alice
o It’s IT5001
escape character
48
Strings
• Double quotes
Example:
o It is IT5001
o It’s IT5001
o “It’s IT5001,” said Alice.
escape character
49
Strings
Doesn’t require escape character for single quote and double quotes within
strings
50
String Manipulations
• String Operators
• String Formatting
51
String Operators
not in x not in y Returns True if string x is not in string y ‘Hi’ not in ‘Hi IT5001’ False
52
String Operators
53
Built-in String Functions
https://docs.python.org/3/library/functions.html
54
Lexicographical Ordering
Unicode of Characters
lexicographical ordering: first the first two letters are compared, and if they
differ this determines the outcome of the comparison; if they are equal, the next
two letters are compared, and so on, until either sequence is exhausted. 55
String Indexing and Slicing
Indexing:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
index T h i s i s I T 5 0 0 1
Slicing:
56
String Indexing and Slicing
Indexing:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
index T h i s i s I T 5 0 0 1
57
String Indexing and Slicing
Indexing:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
index T h i s i s I T 5 0 0 1
58
Immutability of Strings
59
String Methods
• Case Conversion
upper, lower, title, etc.
60
f-strings
• f-strings
Strings prefixed with ‘f’
‘f’ stands for formatted strings
Expressions can be embedded in strings
o Expressions evaluated at run time.
Contains replacement fields, delimited by curly braces
61
Raw Strings
• Raw Strings
62
Conclusion
• Immutability
63
Miscellaneous
Namespaces
64
Namespaces
Enclosed
will be discussed in
subsequent lectures
Local
65
Builtin Namespace
• Check dir(__builtins__)
66
Global Namespace
67
How are objects stored?
Heap Memory
Id (Address) Objects
0x1 2
0x2 2.0
my_int= 0x1
my_float = 0x2
Global Namespace
dir
print
Builtin Namespace
• x=2 x 2
• y=2
• y=3 3
y
• y = 4.0
4.0
69
How are objects stored?
Demo: pythontutor.com
70
Memory Management
71
Data Model: Objects, Values, and Types
72
IT5001 Software Development
Fundamentals
1
Agenda: Functions
2
Why Functions?
3
Example: Drawing a square
5
What if you want more squares?
• How to do it?
Use functions
6
Abstraction
Input Output
• Usability
User only needs to know input arguments and output data types
7
Modularity
A Giant Module
(A program that do many things)
Vs
Modular Architecture
𝑥 𝑦
name of the function 𝑓
one-to-one
𝑦 𝑓 𝑥 many-to-one
Domain Range
9
Functions in Programming
10
Types of Functions
Domain Range
• Pure functions 𝑓
Functions without side-effects
Only mapping
Outputs depend only on inputs
11
Functions in Python
• Built-in Functions
Builtin module is loaded automatically
o No need to import
Examples: print(), input(), id(), etc.
• User-defined Functions
• Special function
main()
12
Built-In Functions
13
https://docs.python.org/3/library/functions.html
Functions from Python Modules and Packages
• Import packages
Example:
o math package
Examples
o import math
o from math import cos, sin
o from math import *
14
Namespaces: Importing Modules
Syntax:
import <module_name>
<module_name>.<object_name>
sin, pi, etc.
Example: dedicated
math
namespace
import math namespace
for each
math.pi imported
math.sin(math.pi/2) module within
global Global
namespace Namespace
dir
print
Builtin Namespace
15
Importing Modules
16
Namespaces: Importing Multiple Modules
Syntax:
statistics
namespace
Example: mean,
variance, etc.
Global
Namespace
dir
print
Builtin Namespace
17
Namespaces: Importing Objects from Modules
Syntax:
Example: Global
Names from Namespace
math module
are imported
into global
namespace
dir
print
Builtin Namespace
18
You don’t want to be like this in real life
• Simple functions
• Doc strings
• Arguments (Parameters)
Positional
Keyword
Default
• Parameter Passing
Pass-by Value
Pass-by Reference
Pass-by Assignment
20
User-Defined Functions
function name
keyword
<statement>
<statement>
def function_name (argument(s)): y = function_name(argument)
<statement>
<statement>
.
<statement>: Statement that is part
. of the function scope
. <statement>: Statement that is out of
<statement> function scope
<statement>
<statement>
white space
(indicates the scope of the function)
21
User-Defined Functions
22
Return Statement
23
Example
𝑥 𝑥
𝑦 𝑓 𝑥 ,𝑥
2
Block of Code
24
Arguments
25
Doc String
26
Types of Arguments
• Positional arguments
• Keyword arguments
• Default/optional arguments
27
Positional Arguments
28
Positional Arguments
29
Keyword Arguments
30
Default/optional arguments
31
Return vs Print
Vs Returns None
32
Revisit Drawing Squares
• Retain similarities
• Parametrize differences
33
Drawing Squares using Functions
34
Namespaces
Builtin
Namespace Global
Enclosed
Local
35
Namespaces: User-defined functions
Local namespace
is created when
the user-defined Local Namespace
function is called
Global Namespace
Builtin Namespace
36
Namespaces: Imported Modules and User-defined
functions
Local namespace
is created with in
global namespace
when the user-
Local Namespace
defined function is
called
imported_module_1
Dedicated Namespace
namespace for
each imported
module imported_module_2
Namespace
Global Namespace
Builtin Namespace
37
Functions: Tracing 1
38
Functions: Tracing 1
0x1 2
0x2 4
Memory
x = 0x1
y = 0x2
Global namespace
Builtin namespace
39
Functions: Tracing 1
0x1 2
0x2 4
Memory
x = 0x1
y = 0x2
Global namespace
Builtin namespace
40
Functions: Tracing 1
0x1 2
0x2 4
Memory
x = 0x1
y = 0x2
Global namespace
Builtin namespace
41
Functions: Tracing 1
0x1 2
0x2 4
0x3 3
0x4 6
x = 0x3
y = 0x4
sum_two_numbers
Memory
x = 0x1
y = 0x2
Global namespace
Builtin namespace
42
Functions: Tracing 1
0x1 2
0x2 4
0x3 3
0x4 6
x = 0x3
y = 0x4
sum_two_numbers
Memory
x = 0x1
y = 0x2
Global namespace
Builtin namespace
43
Functions: Tracing 1
0x1 2
0x2 4
0x3 9
Memory
x = 0x1
y = 0x2
z = 0x3
Global namespace
Builtin namespace
44
Functions: Tracing 2
45
Functions: Tracing 2
0x1 2
0x2 4
Heap Memory
x = 0x1
y = 0x2
Global namespace
Builtin namespace
46
Functions: Tracing 2
0x1 2
0x2 4
Heap Memory
x = 0x1
y = 0x2
Global namespace
Builtin namespace
47
Functions: Tracing 2
0x1 2
0x2 4
Heap Memory
x = 0x1
y = 0x2
Global namespace
Builtin namespace
48
Functions: Tracing 2
0x1 2
0x2 4
0x3 3
x = 0x3
sum_two_numbers
Heap Memory
x = 0x1
y = 0x2
Global namespace
Builtin namespace
49
Functions: Tracing 2
0x1 2
0x2 4
0x3 3
x = 0x3
sum_two_numbers
Heap Memory
x = 0x1
y = 0x2
Global namespace
Builtin namespace
50
Functions: Tracing 2
0x1 2
0x2 4
0x3 3
0x4 7
Heap Memory
x = 0x1
y = 0x2
z = 0x4
Global namespace
Builtin namespace
51
Side-effects
• Pure functions
Functions without side-effects
Only mapping
Outputs depend only on inputs
52
Pure Function
53
Summary
• User-defined functions
• Argument Types
• Print vs Return
• Pure Function
54
IT5001 Software Development
Fundamentals
3. Control Structures
Sirigina Rajendra Prasad
• Why?
delta = 25-24 = 1 > 0
• If delta < 0
The equation has no real solution
Sequence • Default
True False
• Also called ?
Selection branching
• Also called
Repetition
False ?
loop
True
Making Choices
Control Structure: Selection True
?
False
If (a condition is true)
Do A
Else
Do B
Can be MORE THAN one single
instruction
• For example:
If (I have $1000000000000000)
Buy a car
Eat a lot of buffets
Go travel
Quit NUS!
Else
Be good and study
Control Structure: Selection True
?
False
If (a condition is true)
Do A
Else
Do B
Can be MORE THAN one single
• For example: instruction
If (I have $1000000000000000)
If (I am heartless)
Buy a car
Eat a lot of buffets
Go travel
Quit NUS!
Else
donate all the money to charity Nested “if”
Else
Be good and study
Control Structure: Selection True
?
False
If (a condition is true)
Do A
Else
Do B
Can be WITHOUT “else”
• For example:
If (I have $1000000000000000)
Buy a car
Eat a lot of buffets
Go travel
Quit NUS!
Else
Be good and study
Control Structure: Selection True
?
False
If (a condition is true)
Do A
Else
Do B
Can be MORE THAN one single
instruction
• For example:
If (I have $1000000000000000)
Buy a car
Eat a lot of buffets
Go travel
Quit NUS!
Else
Be good and study
Condition
condition
If the condition is True
If the condition is False
Conditional
Syntax Example
if <expr>: >>> my_money = 1000
statement(s) >>> if my_money > 0:
print('Good')
'Good'
indentation
Conditional
Syntax Example
if <expr>: >>> my_money = 1000
statement(s) >>> if my_money > 0:
print('Good')
print('Good')
print('Good')
indentation
'Good'
'Good'
'Good'
Conditional
Syntax Example
if <expr>: >>> my_account = 1000
statement(s) >>> if my_account > 0:
else: print('rich')
statement(s) else:
print('broke')
‘rich'
Conditional (Nested)
Syntax Example
if <expr>: a = 4
if <expr>: if a < 10:
statement(s) if a < 1:
print('Here')
Print nothing
Conditional
Syntax Example
if <expr>: >>> my_account = 1000
statement(s) >>> if my_account < 0:
else: print('poor')
statement(s) else:
if my_account > 1:
Clumsy print(‘v rich')
v rich
Conditional
Syntax Example
if <expr>: >>> a = -3
statement(s) >>> if a > 0:
elif <expr>: print('yes')
statements(s) elif a == 0:
else: print('no')
statement(s) else:
print('huh')
'huh'
Conditional
Syntax Example
if <expr>: >>> a = 4
statement(s) >>> if a > 0:
elif <expr>: print('yes')
statements(s) elif a == 0:
elif <expr>: print('no')
statements(s) elif a == 4:
else: print('ahh')
statement(s) else:
print('huh')
'yes'
Can be many
T F
a < 0
e.g. T F
print(‘yes’) a==0
>>> a = 4
>>> if a < 0:
print('yes')
print(‘no’)
elif a == 0: T F
a==4
print('no')
elif a == 4:
print('ahh')
print(‘ahh’) print(‘huh’)
else:
print('huh')
'ahh'
Homework: Figure out ALL conditions
condition
Repetition
Control Structure: Repetition False ?
• For example
While (I am hungry)
Eat a bun
34
Iterable and Iterators
Can be looped over Repeated calls of next() method return next item
Any object with __iter__ method is iterable from iterator object
Builtin Iterables: If no further items in iterator, next( ) method
range, strings, lists, tuples raises StopIteration exception
User-defined iterable objects
Generator functions
35
Iterables
• This week:
range() - builtin iterable
• Subsequently
strings
user-defined iterators
lists/tuples/dictionary
36
Builtin Iterable: range()
37
Repetition Flow Control: “For”
Syntax Example
for i in range(n,m): for i in range(0,5):
statement(s) print(i)
0
1
2
3 Exclusive
4
Repetition Flow Control: “For”
Example Interpreted as
for i in range(0,5): i=0
print(i) print(i)
i=1
0 print(i)
1 i=2
2 print(i)
3 i=3
4 print(i)
i=4
print(i)
Iterative Factorial
Idea
• Start with 1, multiply by 2, multiply by 3, … , multiply by n.
• 𝑛𝑛! = 1 × 2 × 3 ⋯ × 𝑛𝑛
Product Counter
120
24
1
6
2 × 3
5
4
1
2
Iterative Factorial
• 𝑛𝑛! = 1 × 2 × 3 ⋯ × 𝑛𝑛
• Computationally
• Starting:
• product = 1
• counter = 1
• Iterative (repeating) step:
• product product × counter
• counter counter + 1
• End:
• product contains the result
Computing Factorial
• 𝑛𝑛! = 1 × 2 × 3 ⋯ × 𝑛𝑛
• Factorial rule:
• product product × counter
• counter counter + 1 product counter
non-inclusive.
def factorial(n): Up to n. 1 2
product = 1 1x2 = 2 3
for counter in range(2, n+1): 1x2x3=6 4
product = product * counter
1x2x3x4=24 5
return product
120 6
720 7
factorial(6)
for loop
• sequence
a sequence of values
• var
variable that take each value in the sequence
• body
statement(s) that will be evaluated for each value in the sequence
range function
for i in range(10):
print(i)
Randomly
generate
either 0 or 1
while loop
• while <expression>:
• <body>
• expression
Predicate (condition) to stay within the loop
• body
Statement(s) that will be evaluated if predicate is True
Repetition (Infinite)
while True: a = 0
print(‘Ah...’) while a > 0:
a = a + 1
print(a)
Repetition
indentation
Syntax Example
while <expr>: >>> a = 0
statement(s) >>> while a < 5:
a = a + 1
print(a)
1
2
3
4
5
Another Iterative process
Syntax Example
while <expr>: def nestedWhile():
i = 0
while <expr>: while i < 5:
i += 1
statement(s) j = 0
while j < 3:
j += 1
print ('#' * j)
Repetition, a Very Common
Pattern
9 out of 10 times you will
do For loop
>>> a = 0 for i in range(0,N):
>>> while a < N: do something
a = a + 1
do something
Three Types of Loops
• You do not know how many numbers will the user enter
Why do we need to repeat these?
Loop Terminating Condition
• When
num == ‘bye’? Or
num!= ‘bye’ ?
Loop Terminating Condition
• For example, if you are the teacher with a lot of test scripts, how do you
check if “all are marked”?
Goal: All are Alphabet
In Python, you
indent the
statements
needed to be
loop
Goal: All are Alphabets
• Combining
You check the character one-by-one
o If the current one is NOT alphabet, return “No”!
Until finishing all character all checked, return “Yes”
Goal: All are Alphabets
• Combining
You check the character one-by-one
o If the current one is NOT alphabet, return “No”!
Until finishing all character all checked, return “Yes”
Goal: All are Alphabets
• Combining
You check the character one-by-one
o If the current one is NOT alphabet, return “No”!
Until finishing all character all checked, return “Yes”
Goal: All are Alphabets
• Combining
You check the character one-by-one
o If the current one is NOT alphabet, return “No”!
Until finishing all character all checked, return “Yes”
How many times?
for j in range(10): 0
print(j) 1
Break out
if j == 3: 2
of loop
break Jump 3
print("done") done
def guessANum():
secret = random.randint(0,99) # 0 <= secret <= 99
guess = -1
print('I have a number in mind between 0 and 99')
while guess != secret:
guess = int(input('Guess a number: '))
if guess == secret:
print('Bingo!!! You got it! ')
Repeat
until the
elif guess < secret:
print('Your number is too small')
else: condition
print('Your number is too big') is False
guessANum()
guessANum.py
import random
def guessANum():
secret = random.randint(0,99) # 0 <= secret <= 99
guess = -1
print('I have a number in mind between 0 and 99')
while guess != secret:
guess = int(input('Guess a number: '))
if guess == secret:
print('Bingo!!! The answer is ' + str(secret)))
elif guess < secret:
print('Your number is too small')
else: Repeat
print('Your number is too big') until the
condition
is False
guessANum()
How to write a love letter in Python
def show_my_love():
everything = True
you = everything
my_mind = you
while(my_mind == True):
print('I love you')
How to write a love letter in Python
def show_my_love():
everything = True #Everything I say is true
you = everything #You are everything to me
my_mind = you #All my mind is filled with you
1
Scope
2
Global vs Local Variables
Local namespace
x=0
Global namespace
Builtin namespace
Example
sum_two_numbers
x
y
Global namespace
Builtin namespace
4
Global Variable
foo_printx()
print(x) foo_printx
x=0
Global namespace
Builtin namespace
Global vs Local Variables
x = 999
print(x)
Scope of the global ‘x’
foo_printx()
print(x)
A local ‘x’ that is created within the function
foo_printx() and will ‘die’ after the function
exits
Global vs Local Variables
x = 0
def foo_printx():
x = 999
x = 999
print(x) foo_printx
x=0
foo_printx() Global namespace
Builtin namespace
print(x)
8
Crossing Boundary
x = 0
def foo_printx():
global x foo_printx
x = 999 x=0
print(x) Global namespace
Builtin namespace
foo_printx() Output:
print(x) 999
999
How about… this?
• Local or global?
x = 0
• Error!
• Because the line
def foo_printx(): “x=999” creates a local
print(x) version of ‘x’
x = 999 • Then the first print(x)
print(x) will reference a local x
that is not assigned
with a value
foo_printx() • The line that causes an
error
Parameters are LOCAL variables
Scope of x in
p1
Scope of x in
p2
Scope of x in
p3
Practices (Convention)
Convention:
Usually in all CAPs
Generator Functions
14
Generator Functions
only difference
15
Return vs Yield
16
What is the state of a function?
0x1 2
0x2 4
x
y
Local namespace
Global namespace
Builtin namespace Heap Memory
17
Generator Functions: Examples
18
Generator Functions: Examples
19
Calling Other
Functions
Compare:
def hypotenuse(a, b):
return sqrt(sum_of_squares(a, b))
def square(x): ?
return x * x a
Versus: b
def hypotenuse(a, b):
return sqrt((a*a) + (b*b))
The Call Stack
Michael Caine Just Ended An Eight Year Long Debate Over The Ending Of "Inceptio
Stack
>>> p1(3)
Entering function p1
Entering function p2
Entering function p3
Line before return in p3
Line before return in p2
Line before return in p1
9
FILO!
Going in
Exiting a
function
Namespaces: Calling Other Functions
Global Namespace
Builtin Namespace
29
Namespaces: Calling Other Functions
x =3
Namespace of p1( )
Global Namespace
Builtin Namespace
30
Namespaces: Calling Other Functions
x =3
Namespace of p1( )
x =3
Namespace of p2( )
Global Namespace
Builtin Namespace
31
Namespaces: Calling Other Functions
x =3
Namespace of p1( )
x =3
Namespace of p2( )
x =3
Namespace of p3( )
Global Namespace
Builtin Namespace
32
Namespaces: Calling Other Functions
x =3
Namespace of p1( )
x =3
Namespace of p2( )
x=3
output = 9
Namespace of p3( )
Global Namespace
Builtin Namespace
33
Namespaces: Calling Other Functions
x =3
Namespace of p1( )
x=3
output = 9
Namespace of p2( )
Global Namespace
Builtin Namespace
34
Namespaces: Calling Other Functions
x=3
output = 9
Namespace of p1( )
Global Namespace
Builtin Namespace
35
Namespaces: Calling Other Functions
Global Namespace
Builtin Namespace
36
p3()
p2()
p1()
Recursion
38
Recursion
A Central Idea of CS
Garfield dreaming
recursively.
Sierpinksi triangle
Droste effect
Recursive tree
Mandelbrot Fractal Endless Zoom
Recursion
Calling itself
(smaller problem)
42
Recursive Functions return 4*6 = 24
factorial(3))
return 2*1 = 2
factorial(2))
return 1
factorial(1))
Base Case
43
Namespaces: Recursive Function
n=4
Namespace of factorial(4)
Global Namespace
Builtin Namespace
44
Namespaces: Recursive Function
n=4
Namespace of factorial(4)
n=3
Namespace of factorial(3)
Global Namespace
Builtin Namespace
45
Namespaces: Recursive Function
n=4
Namespace of factorial(4)
n=3
Namespace of factorial(3)
n=2
Namespace of factorial(2)
Global Namespace
Builtin Namespace
46
Namespaces: Recursive Function
n=4
Namespace of factorial(4)
n=3
Namespace of factorial(3)
n=2
Namespace of factorial(2)
n=1
Namespace of factorial(1)
Global Namespace
Builtin Namespace
47
Namespaces: Recursive Function
n=4
Namespace of factorial(4)
n=3
Namespace of factorial(3)
n=2
Namespace of factorial(2)
Namespace of factorial(1)
Global Namespace
Builtin Namespace
48
Namespaces: Recursive Function
n=4
Namespace of factorial(4)
n=3
Namespace of factorial(3)
Global Namespace
Builtin Namespace
49
Namespaces: Recursive Function
n=4
Namespace of factorial(4)
Global Namespace
Builtin Namespace
50
Namespaces: Recursive Function
return value is 24
n=4
Namespace of factorial(4)
Global Namespace
Builtin Namespace
51
Namespaces: Recursive Function
return value is 24
Global Namespace
Builtin Namespace
52
Recursive Vs Iteration
53
Fibonacci Number
(Recursion)
Starting from 2 Rabbits
How many ways to arrange cars?
• And each car can park into one parking space, but a bus needs
two consecutive ones
• If we have 1 parking space, I can only park a car
1 way
• But if there are 2 parking spaces, we can either park a bus or two
cars
2 ways
•
How many ways to arrange cars?
• So if we have 3 parking spaces, how many different ways can we park cars
and buses?
3 ways
How many ways to arrange cars?
• So if we have 4 parking spaces, how many different ways can we park cars
and buses?
5 ways
How many ways to arrange cars?
• 5 parking spaces?
• 6 parking spaces? #parking spaces #ways
0 1
1 1
2 2
3 3
4 5
5 8
6 13
• If it’s a car, there are n - 1 spaces left, you can have the number of way
for n - 1 spaces
Otherwise, it’s the number of way for n - 2 spaces
• So
f (n) = f (n - 1) + f (n - 2) for f(0) = f(1) = 1
Fibonacci Numbers
• Write a fibonacci function that can compute f(n) for n > 1000
Google about Recursion
1
Recursion vs Iteration
Reversing a String
• How about reversing a string? Of course, we can just use string slicing
c output
a a
b ba
c cba
d dcba
e edcba
Reversing String (Recursive Version)
• reverseStringR(‘abcde’)
• reverseStringR(‘bcde’)+’a’
• reverseStringR(‘cde’)+’b’+’a’
• reverseStringR(‘de’)+’c’+’b’+’a’
• reverseStringR(‘e’)+’d’+’c’+’b’+’a’
• reverseStringR(‘’)+’e’+’d’+’c’+’b’+’a’
• ‘’+’e’+’d’+’c’+’b’+’a’
• ‘edcba’
Taylor Series
Taylor Series
• Using iteration
Sum up to n = 1
k
kth
Sum up to n = k - 1
n=k
Computing sine by Recursion
• Assuming that if the function sinR(x,k) sums until n = k, then
k
kth
Sum up to n = k - 1
n=k
Computing sine by Recursion
• Assuming that if the function sinR(x,k) sums until n = k, then
sinR(x,k) = sinR(x,k-1) + the kth term
More Taylor Series
Recursion Common Patterns
Base cases
Base case The answer for previous k – 1 terms The kth term
Iteration/Recursion Conversion
Base case The answer for previous k – 1 terms The kth term
“Homework”
Iteration Recursion
def sum(n): def sum(n):
res = 0 if n == 0:
while n > 0: return 0
res = res + n%10 else:
n = n//10 return n%10 + sum(n//10)
return res
base/initial value stop/base case (they are related, how?)
computation temporary result variables
continuation/next value not needed in recursion (why?)
Factorial
Iteration Recursion
def fact(n): def fact(n):
res = 1 if n == 0:
while n > 0: return 1
res = res * n else:
n = n-1 return n * fact(n-1)
return res
base/initial value stop/base case (they are related, how?)
computation temporary result variables
continuation/next value not needed in recursion (why?)
“Homework”
• How to re-write your code with both iterative/recursion version
mentioned in this course before?
• burgerPrice()
• checkAllAlpha()
• Etc.
• The answer for all k-1 terms?
• Base case?
• Kth term?
Code Refactoring
Code Refactoring
• Refactoring is a disciplined technique for restructuring an existing
body of code, altering its internal structure without changing its
external behavior.
Nested Functions
Nested Functions
• Functions defined inside other functions
x=2
inner_func
Namespace
x=2
enclosing_func Namespace
x=3
inner_func
Namespace
x=2
enclosing_func Namespace
Builtin Namespace
Output:
Nested Functions
Inner functions can access global variables
inner_func
Namespace
enclosing_func Namespace
Builtin Namespace
Output:
Nested Functions
Inner functions cannot modify global variables
x=?
inner_func
Namespace
enclosing_func Namespace
Builtin Namespace
Nested Functions: global keyword
Modifying global variable from inner function
nonlocal/enclosing
namespace
for inner function
global keyword
inner_func
binds this variable to Namespace
global variable x x
enclosing_func Namespace
x Global Namespace
Builtin Namespace
Output:
Nested Functions
Inner functions can access nonlocal variables
inner_func
Namespace
x
enclosing_func Namespace
x Global Namespace
Builtin Namespace
Output:
Nested Functions
Inner functions cannot modify nonlocal variables
inner_func
Namespace
x
enclosing_func Namespace
x Global Namespace
Builtin Namespace
Output:
Nested Functions: nonlocal keyword
Names in enclosing_func namespace
are nonlocal variables for inner_func
inner_func
Namespace
Output: x
enclosing_func Namespace
x=2
Global Namespace
Builtin Namespace
Nested Functions
enclosing function
for p1() and p3()
Global Namespace
Builtin Namespace
39
Namespaces: Nested Functions
x =3
Namespace of p1( )
Global Namespace
Builtin Namespace
40
Namespaces: Nested Functions
x=3
Namespace of p2( )
x=3
Namespace of p1( )
Global Namespace
Builtin Namespace
41
Namespaces: Nested Functions
x=3
output = 9
Namespace
of p3( )
x=3
Namespace of p2( )
x=3
Namespace of p1( )
Global Namespace
Builtin Namespace
42
Namespaces: Nested Functions
output = 9
x=3
Namespace of p2( )
x=3
Namespace of p1( )
Global Namespace
Builtin Namespace
43
Namespaces: Nested Functions
output = 9
x=3
Namespace of p1( )
Global Namespace
Builtin Namespace
44
Namespaces: Nested Functions
Global Namespace
Builtin Namespace
45
What is the output?
What is the output?
Where do we use inner functions?
1
Recursion vs Iteration
Reversing a String
• How about reversing a string? Of course, we can just use string slicing
c output
a a
b ba
c cba
d dcba
e edcba
Reversing String (Recursive Version)
• reverseStringR(‘abcde’)
• reverseStringR(‘bcde’)+’a’
• reverseStringR(‘cde’)+’b’+’a’
• reverseStringR(‘de’)+’c’+’b’+’a’
• reverseStringR(‘e’)+’d’+’c’+’b’+’a’
• reverseStringR(‘’)+’e’+’d’+’c’+’b’+’a’
• ‘’+’e’+’d’+’c’+’b’+’a’
• ‘edcba’
Taylor Series
Taylor Series
• Using iteration
Sum up to n = 1
k
kth
Sum up to n = k - 1
n=k
Computing sine by Recursion
• Assuming that if the function sinR(x,k) sums until n = k, then
k
kth
Sum up to n = k - 1
n=k
Computing sine by Recursion
• Assuming that if the function sinR(x,k) sums until n = k, then
sinR(x,k) = sinR(x,k-1) + the kth term
More Taylor Series
Recursion Common Patterns
Base cases
Base case The answer for previous k – 1 terms The kth term
Iteration/Recursion Conversion
Base case The answer for previous k – 1 terms The kth term
“Homework”
Iteration Recursion
def sum(n): def sum(n):
res = 0 if n == 0:
while n > 0: return 0
res = res + n%10 else:
n = n//10 return n%10 + sum(n//10)
return res
base/initial value stop/base case (they are related, how?)
computation temporary result variables
continuation/next value not needed in recursion (why?)
Factorial
Iteration Recursion
def fact(n): def fact(n):
res = 1 if n == 0:
while n > 0: return 1
res = res * n else:
n = n-1 return n * fact(n-1)
return res
base/initial value stop/base case (they are related, how?)
computation temporary result variables
continuation/next value not needed in recursion (why?)
Towers of Hanoi Problem
• Move entire stack to the last
tower while obeying the
following rules
• Only one disc may be moved at a
time
• Each move consists of taking the
upper disk from one of the stacks
and placing it on top of another
stack or on an empty rod. https://en.wikipedia.org/wiki/Tower_of_Hanoi
Solution:
S A D
Move(3,S,D,A) 1
Move two discs from auxiliary tower to
Move two discs from source tower to destination tower using source tower
auxiliary tower using destination tower
Depth-first
In-order traversal
“Homework”
• How to re-write your code with both iterative/recursion version
mentioned in this course before?
• burgerPrice()
• checkAllAlpha()
• Etc.
• The answer for all k-1 terms?
• Base case?
• Kth term?
Code Refactoring
Code Refactoring
• Refactoring is a disciplined technique for restructuring an existing
body of code, altering its internal structure without changing its
external behavior.
Nested Functions
Nested Functions
• Functions defined inside other functions
x=2
inner_func
Namespace
x=2
enclosing_func Namespace
x=3
inner_func
Namespace
x=2
enclosing_func Namespace
Builtin Namespace
Output:
Nested Functions
Inner functions can access global variables
inner_func
Namespace
enclosing_func Namespace
Builtin Namespace
Output:
Nested Functions
Inner functions cannot modify global variables
x=?
inner_func
Namespace
enclosing_func Namespace
Builtin Namespace
Nested Functions: global keyword
Modifying global variable from inner function
nonlocal/enclosing
namespace
for inner function
global keyword
inner_func
binds this variable to Namespace
global variable x x
enclosing_func Namespace
x Global Namespace
Builtin Namespace
Output:
Nested Functions
Inner functions can access nonlocal variables
inner_func
Namespace
x
enclosing_func Namespace
x Global Namespace
Builtin Namespace
Output:
Nested Functions
Inner functions cannot modify nonlocal variables
inner_func
Namespace
x
enclosing_func Namespace
x Global Namespace
Builtin Namespace
Output:
Nested Functions: nonlocal keyword
Names in enclosing_func namespace
are nonlocal variables for inner_func
inner_func
Namespace
Output: x
enclosing_func Namespace
x=2
Global Namespace
Builtin Namespace
Nested Functions
enclosing function
for p1() and p3()
Global Namespace
Builtin Namespace
42
Namespaces: Nested Functions
x =3
Namespace of p1( )
Global Namespace
Builtin Namespace
43
Namespaces: Nested Functions
x=3
Namespace of p2( )
x=3
Namespace of p1( )
Global Namespace
Builtin Namespace
44
Namespaces: Nested Functions
x=3
output = 9
Namespace
of p3( )
x=3
Namespace of p2( )
x=3
Namespace of p1( )
Global Namespace
Builtin Namespace
45
Namespaces: Nested Functions
output = 9
x=3
Namespace of p2( )
x=3
Namespace of p1( )
Global Namespace
Builtin Namespace
46
Namespaces: Nested Functions
output = 9
x=3
Namespace of p1( )
Global Namespace
Builtin Namespace
47
Namespaces: Nested Functions
Global Namespace
Builtin Namespace
48
What is the output?
What is the output?
Where do we use inner functions?
Fail!
3
4
fact(2.1)
fact(-1)
Common Types of Errors
• Infinite loop (forgot to decrement)
def fact_iter(n):
counter, result = n, 1
while counter!= 0:
result *= counter
return result
Common Types of Errors
• Numerical imprecision counter never exactly equals n
def foo(n):
counter, result = 0,0
while counter != n:
result += counter
counter += 0.1
return result
foo(5)
Common Types of Errors
• Logic
def fib(n):
if n < 2:
return n
else:
return fib(n-1) + fib(n-1)
How to debug?
• Think like a detective
• Look at the clues: error messages, variable values.
• Eliminate the impossible.
• Run the program again with different inputs.
• Does the same error occur again?
How to debug?
• Work backwards
• From current sub-problem backwards in time
• Use a debugger
• IDLE has a simple debugger
• Overkill for our class
• Trace a function
• Display variable values
Displaying variables
debug_printing = True
def debug_print(msg):
if debug_printing:
print(msg)
def foo(n):
counter, result = 0,0
while(counter != n):
debug_print(f'{counter}, {n}, {result}')
counter, result = counter + 0.1, result + counter
return result
Example
def fib(n):
debug_print(f'n:{n}')
if n < 2:
return n
else:
return fib(n-1) + fib(n-1)
Other tips
• State assumptions clearly.
• Non-indexed collection:
– Sets
– Dictionary
Lists and Tuples
• Belongs to a type of data structure called arrays
• Intrinsic ordering
– Easy to retrieve data from the array
• Lists
– Mutable
– Dynamic Arrays
• Tuples
– Immutable
– Static Arrays
3
Lists
• Ordered sequence of data types
– Homogeneous sequence
• Sequence of integers
• Sequence of floats
• Sequence of strings
• Sequence of lists
• Sequence of functions, etc.
– Heterogeneous sequence
• mix of integers, floats, strings, etc.
4
Lists are Referential Arrays
5
All Indexed Sequences can…
a[i] return i-th element of a
a[i:j] returns elements i up to j-1
len(a) returns numbers of elements in sequence
min(a) returns smallest value in sequence
max(a) returns largest value in sequence
x in a returns True if x is a part of a
a + b concatenates a and b
n * a creates n copies of sequence a
Lists are mutable
• Elements can be replaced
• Elements can be added
• Elements can be removed
– A specific element
• If element occurs multiple times, removes first occurrence
– Element at a specific location (index)
– From the end of the list
• Elements can be sorted
– sort()
– Sorted()
• Elements can be reversed
8
Lists are Dynamic-Size Arrays
Elements can be added (appended) Elements can be removed
to the list from the list
9
Append Vs Concatenation
1
10
Append Vs Concatenation
11
Append Vs Concatenation
Strings to Lists and Vice-Versa
13
Strings to Lists and Vice-Versa
14
Aliasing vs Cloning
Aliasing
15
Aliasing vs Cloning
Cloning
16
Sort vs Sorted
• sort() method mutates the list
• sorted() method creates a new sorted list without mutating the original list
17
Reverse
• reverse() method mutates the list
18
Lists of Anything
• A list of ….
– Lists?
Block Diagram
list1 list2
[] []
list3
[]
[] []
22
For loop
>>> for i in range(0,5): >>> for i in [0,1,2,3,4]:
print (i) print(i)
0 0
1 1
2 2
3 3
4 4
For Loop
Output:
Never do this
Why?
25
Mutation and Iteration
• Avoid mutating a list while iterating over the list
26
Example: Find Max in A List of No.
• Syntax:
– [expr for elem in iterable if test]
• Returns an iterable
29
List Comprehension
• Todo:
– create a list:
a_list = [1,2,3,4,5,6,…… , 100]
• You can
List Comprehension
The item really in the list
• Or every i between 1 and
101 (exclusive)
Compare to
𝑏𝑏 = {𝑖𝑖|𝑖𝑖 ∈ 1,101 } ordinary math
equation
List Comprehension
• How do I produce a list of first 10 squared
numbers?
Compare to
𝑏𝑏 = {𝑖𝑖 2 |𝑖𝑖 ∈ 1,101 } ordinary math
equation
List Comprehension
• How do I produce a list of odd numbers less
than 100 Stop (exclusive)
Step
Start
– Like string slicing
List Comprehension
• How do I produce a list of even numbers less
than 100
– Similar to the previous one but start with 2
– Or
Advance: Generate Prime Numbers
• Let’s generate all the prime numbers < 50
• First, generate all the non-prime numbers <50
i is from 2 to 7 get all the multiples of i
(7 = sqrt(50)) from 2*i to 49
Advance: Generate Prime Numbers
• Let’s generate all the prime numbers < 50
• First, generate all the non-prime numbers <50
i is from 2 to 7 get all the multiples of i
from 2*i to 49
• Syntax:
– (expr for elem in iterable if test)
• Returns an iterator
38
Generator Expressions
Output:
Which is better?
Generator Expressions
Output:
40
Sequence in Python
• Indexed collection
– Strings
– Lists
– Tuples
• Non-indexed collection:
– Sets
– Dictionary
Tuples
• A static and an immutable array/list
Task Syntax
Return i-th element a[i]
42
Tuples: Example 1
43
Tuples: Example 2
Immutable:
creates a new tuple – but not assigned
44
Tuples: Example 2
• Differences:
– List is mutable
– Tuple is immutable
46
Tuple
• A Tuple is basically a list but
– CANNOT be modified
Tuples use ‘(‘ and ‘)’
Lists use ‘[‘ and ‘]’
Tuple
• A Tuple is basically a list but
– CANNOT be modified
For a Singleton of List and Tuple…
!!!
A Tuple with only one element
• Correct way
Note the
comma
here
But then, why use Tuple? Or List?
• Is it
1. a tuple of tuples,
2. a tuple of lists,
3. a list of tuples, or
4. a list of lists?
Find all the restaurants near me
• I will code like this
A list
A tuple
Challenge:
Find the nearest THREE restaurants
Instead of ALL
List vs Tuple, Cultural Reason
• List
– Usually stores a large collection of data with the
same type (homogenous)
– E.g. List of 200 student names in a class
• Tuple
– Usually stores a small collections of items with
various data types/concepts (heterogeneous )
– E.g. A single student record with name (string),
student number(string) and mark(integer)
But, violating this “culture” will NOT cause any syntax error
List vs Tuple, Technical Reasons
• Immutable vs
mutable
– Tuple is Write
protected
(Immutable)
Pass By Values
But for List
• Mutable!
!!!
Sequence in Python
• Indexed collection
– Strings
– Lists
– Tuples
• Non-indexed collection:
– Sets
– Dictionary
Sets
• A set is an unordered collection of immutable
elements with no duplicate elements
– Unordered: You cannot get a single element by its
index like s[2]
– No duplicate: every element exists only once in a
set
Python
Tuples use ‘(‘ and ‘)’ Removes
Lists use ‘[‘ and ‘]’ duplicates
Sets use ‘{‘ and ‘}’ for you
Sets
• Some operations are not available because
sets are NOT indexed
a[i] return i-th element of a
a[i:j] returns elements i up to j-1
len(a) returns numbers of elements in sequence
min(a) returns smallest value in sequence
max(a) returns largest value in sequence
x in a returns True if x is a part of a
a + b concatenates a and b
n * a creates n copies of sequence a
Set Operations
• Intersection • A–B
Union
Intersection
A-B
(A | B) – A & B
Sets
Remove like a list
• Non-indexed collection:
– Sets
– Dictionary
Dictionary Word
Its meaning
Word
Its meaning
Dictionary
• You search for the word in the dictionary
• Then look for its meaning
Word Meaning
• Each word has a correspondent meaning
Python Dictionary
• You search for the key in the dictionary
• Then look for its value
Key Value
• Each key has a correspondent value key : value
pair
Index:
From 0 to len(a)-1
Output an item
To set up a dictionary
• Each pair has a key and a value
my_stock = {“apples”:450”,”oranges”:412}
my_stock[“apples”]
>>> 450
my_stock[“apples”] + my_stock[“oranges”]
>>> 862
How is a Dictionary Useful?
>>> my_fruit_inventory.pop(“apples”)
>>> print(my_fruit_inventory)
{‘oranges’:200}
• OR
• Non-indexed collection:
– Sets
– Dictionary
IT5001 Software Development Fundamentals
8. Sequences Contd.
Sirigina Rajendra Prasad
1
Python: Hashability and Immutability
Hashable
2
Returning Multiple Values
Treated as a tuple
Unpacking of tuple
Output:
If you don’t know number of arguments
Unknown number of positional arguments
Output:
If you don’t know number of arguments
Unknown number of keyword arguments
Output:
Accessing Global Variables
• Can a function access (read) a global variable?
• Variable is Immutable
• Yes
• Variable is Mutable
• Yes
Output:
6
Modifying Global Variables
• Can a function modify a global variable with variable declared global within
local function?
• Yes, for both mutable and immutable variables
Output:
7
Modifying Global Variables
• Can a function modify a global variable with variable not declared as global
within local function?
• No, for immutable variables
• Yes, for mutable variables with only the methods that mutate data (append, sort, etc.)
No assignment to variable 𝑥𝑥
Output:
8
Scope
• Passing a mutable variable as argument
Output:
How are arguments passed to functions?
• Pass-by-Value
• An independent (duplicate) copy of argument
argument is passed as input
• Not good if the argument size is very large
• Requires additional memory and execution time 0x0001 2
address
• Pass-by-Reference
• Address of argument is passed and function
access the value from address
• Efficient for arguments of very large size
How about Python?
• Pass-by-Value or Pass-by-Reference?
• Neither of them
equivalent to pass-by-reference
Pass-by-Assignment
• Best Practice
• Pass value by assignment, modify, and reassign
Pass-by-Assignment
• For mutable variables
• Immutable Variable
• Can access global variable
• Cannot modify global variable unless declared global
• Mutable Variable
• Can access global variable
• Can modify the variable
• Need to use global keyword for methods that do not mutate objects
• No need of global keywords for methods that mutate objects
15
How are lists resized with append?
Ternary operator in C
floored-division by 8
if current_size < 9:
𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐_𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠 3
else:
8
6
16
How are lists resized Appending 5th element:
Leads to allocation of space for 3 more elements
with append?
Space of 8 elements is reserved for list
No need to create additional space till list is filled
Empty list
17
How are lists resized with append?
18
How are lists resized with concatenation?
• Always create a new list
• Copies the contents of old list and new list combined
New element
List Append Vs Concatenation
List Append Vs Concatenation
0
1
2 Inserting of new element or
Deletion of an element
3 leads to to relocation of
4 elements in subsequent indices
5
6
7
23
List Vs Tuple: Conclusion
• Slower (concatenation)
Miscellaneous
Dictionary – Bucket Array
𝐴𝐴(ℎ(𝑘𝑘)) = 𝑣𝑣
Key (𝑘𝑘) is mapped to an index (0 to N-1) and Value (𝑣𝑣) is stored in the corresponding bucket
https://research.cs.vt.edu/AVresearch/hashing/index.php 26
Hash Function - ℎ(𝑘𝑘)
Keys Index
Objects
ℎ 𝑘𝑘
27
Hash Function - ℎ(𝑘𝑘)
Objects
Objects
Stage 1: Hash Code
implemented Integers
ℎ 𝑘𝑘 in two stages … , −2, −1,0,1,2, …
28
Hash Code
• Bit representation as hash codes
29
Compression Functions
• Division Method 𝑖𝑖 𝑚𝑚𝑚𝑚𝑚𝑚 𝑁𝑁
30
Collisions Collision occurs if multiple keys produce same hash value
ℎ(𝑘𝑘1 ) = ℎ(𝑘𝑘2 )
31
Collision-Handling
• Separate Chaining
• Open Addressing
• Linear Probing
• Quadratic Probing
• Double Hashing
32
Collision-Handling
• Separate Chaining
0 1 2 3 N-3 N-2 N-1
• Each bucket contains a list of values 𝑣𝑣𝑖𝑖 whose ℎ(𝑘𝑘𝑖𝑖 ) are same
Requires additional list data structure
Slows down the access as the list need to be searched for the key
33
Open Addressing
• Linear Probing
• Quadratic Probing
• Double Hashing
34
IT5001 Software Development
Fundamentals
8. Anonymous Functions
Sirigina Rajendra Prasad
1
Functions
• Traditional Form
square(𝑥𝑥) ↦ 𝑥𝑥 2
• Anonymous Form:
𝑥𝑥 ↦ 𝑥𝑥 2
2
Anonymous Functions
• Python Syntax:
lambda args: expression
3
Functions: Traditional Maths vs 𝜆𝜆-Calculus
Mathematics 𝜆𝜆-Calculus
• Abstraction • Abstraction
• 𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠: 𝑥𝑥 ↦ 𝑥𝑥 2 • 𝑥𝑥 ↦ 𝑥𝑥 2
• 𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠 𝑥𝑥 = 𝑥𝑥 2 • 𝜆𝜆𝜆𝜆. 𝑥𝑥 2
• Application • Application
• 𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠 5 = 52 = 25 • (𝜆𝜆𝜆𝜆. 𝑥𝑥 2 )5 = 52 = 25
4
Functions: 𝜆𝜆-Calculus vs Python
𝜆𝜆-Calculus Python
• Abstraction • Abstraction
• 𝑥𝑥 ↦ 𝑥𝑥 2
• 𝜆𝜆𝜆𝜆. 𝑥𝑥 2
• Application • Application
• (𝜆𝜆𝜆𝜆. 𝑥𝑥 2 )5 = 52 = 25
or Abstraction
Application
5
Examples: Identity Function
𝜆𝜆-Calculus Python
• 𝜆𝜆-Calculus
• 𝜆𝜆𝜆𝜆. 𝑥𝑥
• Takes a variable
𝑥𝑥 as input argument
• returns 𝑥𝑥
6
Examples: Constant Function
𝜆𝜆-Calculus Python
• 𝜆𝜆-Calculus
• 𝜆𝜆𝜆𝜆. 𝑦𝑦
• Takes a variable 𝑥𝑥 and
return 𝑦𝑦
Alternative in Python:
7
Anonymous Functions: More Examples
8
IT5001 Software Development
Fundamentals
1
Functions in Python
• Functions can be
Assigned to variables
2
“Callability”
• A function is callable
3
Assignments
• Can!!!!!!
4
Assignments
5
See the difference
values
types
6
Assigning to a variable
Output:
7
Functions can be stored in variables
Equivalent
to cos(0)
The type is
“function”
8
Functions as elements in Lists/Tuples
Output:
Output:
9
Functions as elements in Dictionaries
function as key
10
Functions as input arguments
Function calling
other function
Nested function
Output:
11
Functions that return functions
Closures
Decorators
12
Closures
• Closure:
Returns inner functions
Function plus the environment (state) in which they execute together
Preserve function state across function calls
• Example:
Access to variable
from outer function
13
Closures
14
Decorators
• Decorator is a closure
Additionally, outer function accepts a function as input argument
• Example
15
Function Composition
Equivalent to
16
Mix and Match
A function
A variable
(can be a
function
too!)
Equivalent to
17
Examples
18
The “Powerful” Lambda
19
Agar Agar (Anyhow) Derivative
20
Agar Agar (Anyhow) Derivative
𝑑𝑑 sin 𝑥𝑥
• = cos 𝑥𝑥
𝑑𝑑𝑑𝑑
𝑑𝑑 (𝑥𝑥 3 +3𝑥𝑥−1)
• = 3𝑥𝑥 2 + 3
𝑑𝑑𝑑𝑑
21
Agar Agar (Anyhow) Derivative
𝑑𝑑 sin 𝑥𝑥
Derivatives cos 𝑥𝑥
𝑑𝑑𝑑𝑑
22
Agar Agar (Anyhow) Derivative
𝑑𝑑 sin 𝑥𝑥
Derivatives cos 𝑥𝑥
𝑑𝑑𝑑𝑑
23
Agar Agar (Anyhow) Derivative
24
Agar Agar (Anyhow) Derivative
25
Agar Agar (Anyhow) Derivative
Take in a function,
returning another
function
26
Agar Agar (Anyhow) Derivative
𝑑𝑑 sin 𝑥𝑥
Derivatives cos 𝑥𝑥
𝑑𝑑𝑑𝑑
27
Application Example
of deriv()
28
Example: Newton’s method
29
Example: Newton’s method
30
Example: Newton’s method
• To compute the root of function g(x), i.e. find x such that g(x) = 0
31
Example: Newton’s method
32
Example: Newton’s method
33
34
You can solve any
equation!
…. that Newton Method can solve.
35
IT5001 Software Development
Fundamentals
1
Functions in Python
• Functions can be
Assigned to variables
2
“Callability”
• A function is callable
3
Assignments
• Can!!!!!!
4
Assignments
5
See the difference
values
types
6
Assigning to a variable
Output:
7
Functions can be stored in variables
Equivalent
to cos(0)
The type is
“function”
8
Functions as elements in Lists/Tuples
Output:
Output:
9
Functions as elements in Dictionaries
function as key
10
Functions as input arguments
Function calling
other function
Nested function
Output:
11
Functions that return functions
Closures
Decorators
12
Closures
• Closure:
Returns inner functions
Function plus the environment (state) in which they execute together
Preserve function state across function calls
• Example:
Access to variable
from outer function
13
Closures
14
Decorators
• Decorator is a closure
Additionally, outer function accepts a function as input argument
• Example
15
Function Composition
Equivalent to
16
Mix and Match
A function
A variable
(can be a
function
too!)
Equivalent to
17
Examples
18
The “Powerful” Lambda
19
Agar Agar (Anyhow) Derivative
20
Agar Agar (Anyhow) Derivative
𝑑𝑑 sin 𝑥𝑥
• = cos 𝑥𝑥
𝑑𝑑𝑑𝑑
𝑑𝑑 (𝑥𝑥 3 +3𝑥𝑥−1)
• = 3𝑥𝑥 2 + 3
𝑑𝑑𝑑𝑑
21
Agar Agar (Anyhow) Derivative
𝑑𝑑 sin 𝑥𝑥
Derivatives cos 𝑥𝑥
𝑑𝑑𝑑𝑑
22
Agar Agar (Anyhow) Derivative
𝑑𝑑 sin 𝑥𝑥
Derivatives cos 𝑥𝑥
𝑑𝑑𝑑𝑑
23
Agar Agar (Anyhow) Derivative
24
Agar Agar (Anyhow) Derivative
25
Agar Agar (Anyhow) Derivative
Take in a function,
returning another
function
26
Agar Agar (Anyhow) Derivative
𝑑𝑑 sin 𝑥𝑥
Derivatives cos 𝑥𝑥
𝑑𝑑𝑑𝑑
27
Application Example
of deriv()
28
Example: Newton’s method
29
Example: Newton’s method
30
Example: Newton’s method
• To compute the root of function g(x), i.e. find x such that g(x) = 0
31
Example: Newton’s method
32
Example: Newton’s method
33
34
You can solve any
equation!
…. that Newton Method can solve.
35
Lambda functions
Lambda functions
(
f = lambda a, b: (lambda x: b(b(a))) )
(
f = lambda a, b: (lambda x: b(b(a))) )
(f (‘b’, lambda a: a*3))( (lambda a: a[:1]))
lambda x: ((lambda a: a*3)(lambda a: a*3)(‘b’)))
lambda x: ( ‘bbbbbbbbb’)
(f (‘b’, lambda a: a*3))( (lambda a: a[:1]))
‘bbbbbbbbb’
39
(Text) File Input/Output
You can
download any
data!
Open in
• Excel
• Notepad
Let’s Do it in Python
• Of course, you are not going to type the data
into your Python code
– one data one code?!
– change in data = change in code?
– Called “Hard Coding”
• Usually practice
– Data file +
– Python code that can read the file
Writing A File
Actually Easier
Writing A File
Indicate the file
object f is for writing
The file as an
“iterable”
console echo
Annoying newline
character ‘\n’
A string
Let’s Split!
Split by
space!!!
Let’s Split Commas!
Let’s manage our data
• We want to plot the year against the birthday
– The value of the birth rate is x per thousand
– So the actual no. of birth is x times 1000
Convert
into integers
Discard the
first line
“line”
Discard the
first line
“line”
Discard the
first line
“line”
Now You Know Why “Baby Bonus”
Read in a Reading CSV Files Create a CSV File
CSV file Reader
into a list
Remember these
four lines of code
[5,1,4,9,11,22,12,55]
⬇
[25, 1, 16, 81, 121, 484, 144, 3025]
Squaring/Scaling a Sequence
• Other than the function name (that can change to anything), what is
the difference?
• Conclusion
• Conversion from a map object to
a tuple or list only once
Kattis Demo
• https://open.kattis.com/problems/electricaloutlets
Python’s Filter
Python’s Filter
• Python’s map()
• Apply a function f to every item x in the sequence
• Python’s filter()
• Apply a predicate function f to every item x in the sequence
• A predicate is a function that return True or False
• Return an iterable that
• Keep the item if f(x) returns True
• Remove the item otherwise
Python’s filter()
Counting a Sequence
Shallowly or Deeply
How to Count the Number of Element in a
Sequence?
• And this can handle if the first item is a list of a list of a list of ….
• e.g.
• [[[[[1,2],2],4],2],3,4,5]
Second Question
• If the first item is NOT a list, e.g. [1,2,3,4,[2,3,4],[1]]
• count of the first item is 1
• If the first item IS a list, e.g. [[1,2],3,4,5]
• recursively compute deepcount() of the first item!
Simple Test
deepcount([1])
⬇
deepcount(1) + deepcount([])
Whenever we
reached this line
Count + 1
Simple Test
deepcount([1,2,3])
⬇
deepcount(1) + deepcount([2,3])
⬇
deepcount(2) + deepcount([3])
⬇
deepcount(3) + deepcount([])
x
Tracing the Code
[]
• x = [[[1,2],3],9,[1,2]]
[] 9 []
[] 3 1 2
1 2
x
Tracing the Code
[]
deepcount([[[1,2],3],9,[1,2]])
[] 9 []
[] 3 1 2
deepcount([[1,2],3])+deepcount([9,[1,2]])
1 2
x
Let’s Consider the Left Term
[]
deepcount([[1,2],3])
[] 9 []
deepcount([1,2]) + deepcount([3])
[] 3 1 2
deepcount(1) + deepcount([2]) 1 2
deepcount(2)+deepcount([]) deepcount(3)+deepcount([])
x
Let’s Consider the Left Term
[]
deepcount([[1,2],3])
[] 9 []
deepcount([1,2]) + deepcount([3])
[] 3 1 2
deepcount(1) + deepcount([2]) 1 2
deepcount(2)+deepcount([]) deepcount(3)+deepcount([])
x
Let’s Consider the Left Term
[]
deepcount([[1,2],3]]) ☞ 3
[] 9 []
[] 3 1 2
1 2
x
Tracing the Code
[]
deepcount([[[1,2],3],9,[1,2]])
[] 9 []
[] 3 1 2
deepcount([[1,2],3]])+deepcount([9,[1,2]])
1 2
3 +deepcount([9,[1,2]])
x
Tracing the Code
[]
deepcount([9,[1,2]])
[] 9 []
deepcount(9)+deepcount([[1,2]])
[] 3 1 2
deepcount([1,2]) + deepcount([])
1 2
deepcount(1) + deepcount([2])
deepcount(2) + deepcount([])
x
Tracing the Code
[]
deepcount([9,[1,2]])
[] 9 []
deepcount(9)+deepcount([[1,2]])
[] 3 1 2
deepcount([1,2]) + deepcount([])
1 2
deepcount(1) + deepcount([2])
deepcount(2) + deepcount([])
x
Tracing the Code
[]
deepcount([9,[1,2]]) ☞ 3
[] 9 []
[] 3 1 2
1 2
x
Tracing the Code
[]
deepcount([[[1,2],3],9,[1,2]])
[] 9 []
[] 3 1 2
deepcount([[1,2],3]])+deepcount([9,[1,2]])
1 2
3 + 3 = 6
x
Tracing the Code
[]
• x = [[[1,2],3],9,[1,2]]
[] 9 []
[] 3 1 2
1 2
How about ….
• DeepSquare?
[deepSquare(2)] + deepSquare([])
[2*2] + [] ☞ [4]
DeepInc
• How different from DeepSquare?
deepMap !!!!
deepMap!!!
Remember List Copy by copy()?
• And it works!
Why Do I Want to Go
“Deep”?
Copying a Directory
• When the directory contains a
lot of files in many
subdirectories
Computer Animation
• Skeleton animation
Shortest Path Tree
Image Processing
• An image is a list of lists of lists
• The first level list: rows
• The second level of lists: column
• The third level of lists: RGB values
• Map a function to change
certain values
• E.g. change colors
How about if I just want to
be shallow?
How about if I just want to be shallow?
• Given a nested list, output a list with all the elements but without any
Flatten()
flatten([[[1]]])
flatten([[1]]) + flatten([])
flatten([1]) + flatten([]) + flatten([])
flatten(1) + flatten([]) + flatten([]) + flatten([])
[1] + flatten([]) + flatten([]) + flatten([])
Conclusions
• map() is a powerful tool in Python
• Allows you to perform a lot of operations with less redundant code
• Deep operations are useful to solve problems with non-linear data
• E.g. Trees, n-dim arrays, graphs
• Using recursive functions wisely is the key for algorithms
• Higher level of coding
Dimensions
• Are we living in a three dimensional space?
Rm 1 Rm 2 Rm 3 Rm 4 Rm 5
One Dimension
My room is 02-05
Hotel (2D)
4F 1 2 3 4 5 6
3F 1 2 3 4 5 6
2F 1 2 3 4 5 6
1F 1 2 3 4 5 6
Chess Position
• Row 8
• Col B
• So, B8
Dimensions
One Dimensional Array, A Two Dimensional Array, M
Index Contents
0 1 2 3
0 ‘Apple’
0 ‘Apple’ ‘Lah’ ‘Cat’ ‘Eve’
1 ‘John’
1 ‘Hello’ ‘Pay’ ‘TV’ ‘Carl’
2 ‘Eve’
2 ‘What’ ‘Bank’ ‘Radio’ ‘Ada’
3 ‘Mary’
3 ‘Frog’ ‘Peter’ ‘Sea’ ‘Eat’
4 ‘Ian’
Column index
Row index
• Equivalent to
1 2
3 4
What is the Difference Between …
• A list of lists • 2D Array
– More specifically, all the – Is a subset of a list of lists
lists do not have to be #rows,
the same length Can be any length
Length = 3 Can be any length, but
Length = 3 all the lists have to be
the same length
[[1,2],[3,4,5],[6]] [[1,2],[3,4],[5,6]]
Length = 2 Length = 3 Length = 1 Length = 2 Length = 2 Length = 2
↕
1 2
3 4
A Larger 2-d Array
• Creating a 4 x 10 matrix
pprint() from
the package
pprint makes
the format nicer
Number of rows
Number of columns
To Create an N x N Identical Matrix
Row i
Column j
2D Looping
• Let’s say we just want to print 0 and 1
2D Looping
• Let’s say we just want to print 0 and 1
j=0123456789
↓↓↓↓↓↓↓↓↓↓
i=0→
i=1→
i=2→
i=3→
i=4→
Row i i=5→
i=6→
i=7→
i=8→
i=9→
Column j
To Create an R x C Zero Matrix
Accessing Entries
• Remember
– Frist row index
– Then column index
i=1→
↑
j=3
2D Array Applications
• Matrix operations
• Recoding 2D data
– Tables
– Spatial Data
Matrix Addition
• How do to Matrix
Multiplication or
other matrix
operations, e.g.
inverse, transpose?
Tables
• Just like other Spreadsheet applications
Name Stu. No. English Math Science Social Studies
John A1000000A 90 80 100 70
Peter A1000009D 60 100 60 90
Paul A1000003C 80 80 70 90
Mary A1000001B 100 70 80 80
Tables
• Like in Spreadsheet applications
Name Stu. No. English Math Science Social Studies
John A1000000A 90 80 100 70
Peter A1000009D 60 100 60 90
Paul A1000003C 80 80 70 90
Mary A1000001B 100 70 80 80
• Challenge
– Given the row and column indices i and j, how to
compute the position pos?
A Simple TTT Game
• First, for a matrix game that represent the
current state of the game, let’s make a
function to print it nicely
A Simple TTT Game
Create the game
board
A Simple TTT Game
Put the number 1 to
9 into the board for
display purposes
A Simple TTT Game
There are two players,
Player 0 and Player 1
Player 0 uses ‘X’
Player 1 uses ‘O’
[100,20
Red, green, blue
0,100] = [100,200,100]
2D and 3D Arrays
2D Arrays 3D Arrays
• A list of lists • A list of lists of lists
• A vehicle loading with • A vehicle loading with
vehicles vehicles loading with
– And each vehicle contains vehicles
some passengers – And each vehicle contains
some passengers
2+1 = 3D Array as a Picture
One pixel is a list
of three values of
red, blue and
green.
Usually ranging
from 0 to 255
imshow() is to
draw a picture in
bitmap
imshow() is to
draw a picture in
bitmap
• 3 x 3 pixels (zoomed)
Dimensions
One Dimensional Array, A Two Dimensional Array, M
Index Contents
0 1 2 3
0 ‘Apple’
0 ‘Apple’ ‘Lah’ ‘Cat’ ‘Eve’
1 ‘John’
1 ‘Hello’ ‘Pay’ ‘TV’ ‘Carl’
2 ‘Eve’
2 ‘What’ ‘Bank’ ‘Radio’ ‘Ada’
3 ‘Mary’
3 ‘Frog’ ‘Peter’ ‘Sea’ ‘Eat’
4 ‘Ian’
Remember these
four lines of code
• There are always some rules to control how to modify the attributes
• In real life, how do you withdraw money from your account?
“Rules”
• Can you walk in the bank and get any amount even more than your
balance? Or any other bank transactions?
• Must through some “mechanism”, e.g.
• Bank tellers, ATM, phone/internet banking, etc.
• And these mechanisms have some rules,
• E.g. you cannot withdraw more than your balance
Bank Accounts with “Methods”
Attributes
Methods
Bank Accounts with “Methods”
>>> myAcc = BankAccount('Alan',1000)
>>> myAcc.showBalance()
Your balance is $1000
>>> myAcc.withdraw(123)
123
>>> myAcc.showBalance()
Your balance is $877
>>> myAcc.withdraw(99999)
Money not enough! You do not have $99999
0
Is it a *really* a new thing?
• Recall your previous lectures…
lst = [1, 2, 3]
lst.append(4)
lst [1, 2, 3, 4]
Sportscar Lorry
• Methods • Attributes
• __init__() • cargo
• turnOnTurbo() • Methods
• __init__()
• load()
• unload()
• inventory()
The Classes Vehicle and Sportcar
Sportscar Lorry
• Methods • Attributes
• __init__() • cargo
• turnOnTurbo() • Methods
• __init__()
• load()
• unload()
• inventory()
Inheritance
• Objects that exhibit similar functionality should “inherit” from the
same base object, called the superclass.
• An object that inherits from another is called the subclass.
Subclass and
Superclass
• Usually a subclass is a more
specific type of its parent
class
• Like our classification of
animals, any “children” in
the tree is a more “specific”
type of the “parents”
• (Unless we talk about
multiple inheritance later)
Let’s define a new class Bisarca
• Car carrier trailer
• It is a type of truck that carries other cars
• The truck and also load and unload, but only for cars
• not any type of cargos
Where should
we put class Vehicle
Bisarca? • Attributes: pos,velocity
• Methods:__init__(),setVelocity(),move()
Sportscar Lorry
• Methods: __init__(), • Attributes: cargo
turnOnTurbo() • Methods:__init__(),load(),unload()
,inventory()
Bisarca
• Methods: load()
Class Bisarca
Bisarca
• Methods: load()
Multiple Inheritance
Let’s Create a Class Cannon
Class Cannon
• Sample run:
>>> myCannon = Cannon()
>>> myCannon.fire()
No more ammo
>>> myCannon.reload()
Cannon reloaded
>>> myCannon.reload()
Unable to reload
>>> myCannon.fire()
Fire!!!!!!!
>>> myCannon.fire()
No more ammo
What Do You Have When You…
• Merge a cannon and a vehicle?
+ =
We Want to Have BOTH!
>>> myTank = Tank((0,0))
>>> myTank.setVelocity(40,10)
>>> myTank.move()
Move to (40, 10)
>>> myTank.move()
Move to (80, 20)
>>> myTank.reload()
Cannon reloaded
>>> myTank.fire()
Fire!!!!!!!
Where should we put the class Tank?
Vehicle Cannon
• Attributes: pos,velocity • Attributes: numAmmo
• Methods: setVelocity(),move() • Methods: fire()
Bisarca
• Methods: load()
A Bit Trouble
• Which constructor __init__() should the Tank call?
Call BOTH!!!
Resolving Methods
So far we have
Vehicle Cannon
• Attributes: pos,velocity • Attributes: numAmmo
• Methods: setVelocity(),move() • Methods: fire()
Bisarca
• Methods: load()
What Do You Have When You…
• Merge a Bisarca and a Cannon?
+ =
Let’s Construct Class BattleBisarca
Lorry
• Attributes: cargo Which
• Methods:__init__(),load() load() is
,unload(),inventory()
called by
Bisarca BattleBisarca
• Methods: load() ?
BattleBisarca
Vehicle Cannon
• Attributes: pos,velocity • Attributes: numAmmo
• Methods: setVelocity(),move() • Methods: fire()
Lorry
• Attributes: cargo The nearest
• Methods:__init__(),load() one will be
,unload(),inventory()
called
Bisarca
• Methods: load()
BattleBisarca
Let’s Constuct Class BattleBisarca
Python??
Image Processing
Installing Python Packages
• Python comes with built-in functions
• However, you need to manually install
additional packages
– In Assignment 0, the instructions asked you to
install, imageio, numpy, etc
• In this lecture we will need “imageio”
– To install “imageio” (or any other packages), go to
cmd.exe
• Type “pip install imageio”
• Provided you have your internet connected
• pip will download the package and install it
for you
We have all these photo apps
https://www.everydayfamily.com/slideshow/10-hilariously-awful-photoshop-fails/
Image Processing
• To load an image, you can use the package
“imageio”
Image Processing
• 600 x 600 pixel
– And each pixel has
three values of R, G
and B
– [R, G, B]
Image Processing
Col 0 Col 1 Col 2 …… Col 599
• 600 x 600 pixel Row 0 (R,G,B) (R,G,B) (R,G,B) (R,G,B)
– [R, G, B] Row 1 (R,G,B)
Row 2 (R,G,B)
– 0 <= R,G,B <=255
.
.
.
.
.
.
• every pixel
multiply by
– [R,G,B] x [0,1,0] =
– [R x 0, G x 1, B x 0]
– [0, G, 0 ]
Array Broadcasting
“Broadcasting”
dim[0]
(xcenter,ycenter)
dim[1]
Making a Mask
If the pixel is out
of the circle
Blending on x
NO Blending on
colors
Blending on y
Applying Filters
• sigma = (3,3,1) • sigma = (9,9,1)
Edge Detection
• Anyhow generate an image
More in Numpy and Scipy
• Fourier Transform
• Uniform filter
• Histogram
• Laplace… etc
• More on
– https://docs.scipy.org/doc/scipy/reference/ndimage.h
tml
PILLOW
A Fork in PIL
PILLOW is a fork of PIL
• PIL stands for Python Imaging Library
Let’s get the secret out
PILLOW
• Cannot escape!
PILLOW
Original
Blurred Sharpen
Copy And Paste Copy (crop)
the part of
the picture
Paste it on
the position
(0,400)
Other operations
• resize
• rotation/flipping
• traspose
• Drawing shapes
• etc. etc..
https://pillow.readthedocs.io/en/stable/
Other Than Scipy and Numpy
• OpenCV
• skimage
– scikit-image
Searching
Searching
• You have a list.
• How do you find something in the list?
5 2 3 4
Found 3.
Linear Search
Idea: go through the list from start to finish
# equivalent code
for i in [5, 2, 3, 4]:
if i == 3:
return True
Linear Search
Implemented as a function:
def linear_search(value, lst):
for i in lst:
if i == value:
return True
return False
Why?
IDEA
If list is sorted, we can
“divide-and-conquer”
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Repeat
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Repeat
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Repeat
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Repeat
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Repeat
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Repeat
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Repeat
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Repeat
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Repeat
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Repeat
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Repeat
Unsorted
Sorted Smallest
Obvious Way
Find the smallest card not in hand (SCNIH), and put it at the
end of your hand. Repeat.
Done
Unsorted
Sorted Smallest
There is actually a name for this:
Selection Sort!
Let’s Implement it!
a = [4,12,3,1,11]
sort = []
while a: # a is not []
smallest = a[0]
for element in a:
if element < smallest:
smallest = element
a.remove(smallest)
sort.append(smallest)
print(a)
Output
[4, 12, 3, 11]
[4, 12, 11]
[12, 11]
[12]
[]
print(a)
[]
print(sort)
[1, 3, 4, 11, 12]
Order of Growth?
• Time: Worst
Average
Best
• Space:
Let’s try something
else…
suppose you have a
friend
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Split into halves
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Split into halves
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
Doing it with a friend
• Split cards into two halves and sort. Combine halves
afterwards. Repeat with each half.
How to merge?
How to merge?
• Compare first element
• Take the smaller of the two
• Repeat until no more elements
Merging
def merge(left, right):
results = []
while left and right:
if left[0] < right[0]:
results.append(left.pop(0))
else:
results.append(right.pop(0))
results.extend(left)
results.extend(right)
return results
Order of Growth?
• Time: Worst
Average
Best
• Space:
No need to memorize
Sort Properties
In-place: uses a small, constant amount of
extra storage space, i.e., space
Create 100M of
numbers, estimated
to be 400MB of data
Output:
Let’s calculate
• 400M of data needs 6 seconds
• 15 Exabyte of data needs how long?
- 15 EB = 15 x 1024 x 1024 x 1024 x 1024 MB
- To search through 15EB of data…..
•7845 years…..
• Space
In CS, we consider
• Time
• how long it takes to run a
program
• Space
• how much memory do we
need to run the program
Order of Growth Analogy
• Suppose you want to buy a Blu-
ray movie from Amazon
(~40GB)
• Two options:
• Download
• 2-day Prime Shipping
• Which is faster?
The Infinity Saga Box Set
Order of Growth Analogy
• Buy the full set?
• 23 movies
• Two options:
• Download
• 2-day Prime Shipping
• Which is faster?
Order of Growth Analogy
• Or even more movies?
Download vs Delivery
Time
Download
2 days Delivery
1 hour
# of movies
Ultimate Question
• If the ”volume” increased
• How much more resources, namely time and space,
grow?
Will they grow in the same manner?
• From • From
• factorial(10) • fib(10)
• To • To
• factorial(20) • fib(20)
• To • To
• factorial(100) • fib(100)
• To • To
• factorial(10000) • fib(10000)
Order of Growth
•is NOT…
•The absolute time or space a program
takes to run
•is
•the proportion of growth of the
time/space of a program w.r.t. the growth
of the input
Let’s try it on something we know
def factorial(n):
if n <= 1:
return 1
else:
return n * factorial(n – 1)
def fib(n):
if (n == 0):
return 0
elif (n == 1):
return 1
else:
return fib(n – 1) + fib(n – 2)
Let’s try it on something we know
nfact, nfib = 0,0
def factorial(n):
global nfact
nfact +=1
if n <= 1:
return 1
else:
return n * factorial(n – 1)
def fib(n):
global nfib
nfib +=1
if (n == 0):
return 0
elif (n == 1):
return 1
else:
return fib(n – 1) + fib(n – 2)
Compare
>>> factorial(5) >>> fib(5)
120 5
>>> nfact >>> nfib
5 15
>>> nfact = 0 >>> nfib = 0
>>> factorial(10) >>> fib(10)
3628800 55
>>> nfact >>> nfib
10 177
>>> nfact = 0 >>> nfib = 0
>>> factorial(20) >>> fib(20)
2432902008176640000 6765
>>> nfact >>> nfib
20 21891
Order of Growth of Factorial
>>> factorial(5)
factorial(5)
120
• Factorial is simple
>>> nfact • If the input is n, then the function factorial(4)
5 is called n times
>>> nfact = 0
>>> factorial(10)
• Because each time n reduced by 1
factorial(3)
3628800 • So the number of times of
>>> nfact
10
calling the function is factorial(2)
>>> nfact = 0 proportional to n
>>> factorial(20) factorial(1)
2432902008176640000
>>> nfact
20
Fib
• More complicated >>> fib(5)
5
>>> nfib1
5
>>> nfib = 0
>>> fib(10)
55
>>> nfib
177
>>> nfib = 0
>>> fib(20)
Why?
6765
>>> nfib
21891
Fibonacci: Tree recursion root
fib(5)
fib(4) fib(3)
1 1 0 1 0
fib(1) fib(0)
Can we do better?
Hill-Climbing for Sorting
• Optimization algorithm
• Require an evaluation function
• Example: 𝑉𝑉𝑉𝑉𝑉𝑉𝑉𝑉𝑉𝑉(𝑚𝑚𝑚𝑚_𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙) = 4 + 1 + 2 + 1 = 8
𝑉𝑉𝑉𝑉𝑉𝑉𝑉𝑉𝑉𝑉(𝑚𝑚𝑚𝑚_𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙) = 0 + 0 + 0 + 0 = 0
Hill-Climbing for Sorting
fib(4) fib(3)
1 1 0 1 0
fib(1) fib(0)
1 0
We save the result when
it was computed
Memoization
• Create a dictionary to
remember the answer
if fibm(n) is
computed before
• If the ans was
computed before, get
the answer from the
dictionary
• Otherwise, compute
the ans and put it into
the dictionary for later
use
Can you use Memoization to
compute nCk?
Recursion Removal
• Wait a min…
• Do we need all the past
numbers if we only need
fib(n)?
Recursion Removal 2
• Add a new fib(i)
• as fib(i-1) + fib(i-2)
• And I only need to keep fib(i-1) and fib(i-2)
Improvement
• For IT5001, you should know how to compute fib(n) with time
proportional to n
• The fastest algorithm to compute fib(n) with time proportional to log n
• To know more about this to improve human race and save the world
• CS1231, CS2040, CS3230, etc
• What you learn today is called the Big O notation
• O(n), O(log n), O(n2), O(n log n), O(2n), etc
Errors And Exception
Types of Errors
• Until now error messages haven’t been more than mentioned, but
you have probably seen some
• Two kinds of errors (in Python):
1. Syntax errors
2. Exceptions
Syntax Errors
>>> while True print('Hello world')
SyntaxError: invalid syntax
Exceptions
• Errors detected during execution are called exceptions
• Examples:
Type of Exception Description
NameError If an identifier is used before assignment
TypeError If wrong type of parameter is sent to a function
ValueError If function parameter has invalid value (Eg: log(-1))
ZeroDivisionError If 0 is used as divisor
StopIteration Raised by next(iter)
IndexError If index is out of bound for a sequence
KeyError If non-existent key is requested for set or dictionary
IOError If I/O operation fails (eg: opening a file)
EOFError If end of file is reached for console of file input
AttributeError If an undefined attribute of an object is used
NameError
>>> 4 + spam*3
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
4 + spam*3
NameError: name 'spam' is not defined
TypeError
>>> '2' + 2
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
'2' + 2
TypeError: Can't convert 'int' object to str
implicitly
ValueError
>>> int('one')
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
int('one')
ValueError: invalid literal for int() with base
10: 'one'
ZeroDivisionError
>>> 10 * (1/0)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
10 * (1/0)
ZeroDivisionError: division by zero
Other Common Errors
StopIteration Error
IndexError
KeyError
Handling Exceptions (Errors)
10
Handling Exceptions
• Two Approaches
11
12
Guard Clauses
13
Raising Exceptions
14
Raising Exceptions
16
Raising Exceptions checking for multiple types
17
Guard Clauses: Use with Caution
• Python can raise exceptions without explicit guard clauses
• Checking for a specific exception may consume resources (eg: time)
• Especially if it is done within a loop with several iterations
18
Handling Exceptions
19
Handling Exceptions
• The simplest way to catch and handle exceptions is with a try-except
block:
x, y = 5, 0
try:
z = x/y
except ZeroDivisionError:
print("divide by zero")
How it works
30
Try-Except: Multiple Exceptions
Check each exception and
provide specific message
31
Try-Except: Multiple Exceptions
Check for multiple exceptions
simultaneously
32
Checking for all exceptions
33
Try-Except-Finally
34
Exception Types
• Built-in Exceptions:
https://docs.python.org/3/library/exceptions.html
• User-defined Exceptions
User-defined Exceptions I
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
User-defined Exceptions II
try:
raise MyError(2*2)
except MyError as e:
print('Exception value:', e.value)
Exception value: 4
raise MyError('oops!')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'
Assertion
• For example, in tic-tac-toe, you also assume the position is from 1 to 9
• For a lot of situations, you ”assume” certain conditions in your code, e.g.
• A sorting function will only take sequences as input
• A function checking prime number will only take in integers
• In a certain part of your code, you expect some index 𝑖𝑖 will not exceed a certain
range
• In Python, you can simply add an assertion
• If the statement following in the assertion is False, then EXCEPTIONS!
• Raises an AsserionError
Example
VS
Why Visualization?
• Meet the need for speed
• For yourself, a tool to understand your data
• For your audience
– Addressing data quality
– Displaying meaningful results
– Dealing with outliers
• For yourself, for your supervisors, for your
boss!
Numpy
• A convenient package • For example, if you
• You can get around with want to create a list of
“normal” Python numbers from 0 to π
method but Numpy can without Numpy you
shorten your code a lot have to:
Numpy
Be Careful!!!
This is not “arrange”
but “arange”
Another Way Be Careful!!!
This is not
“linespace” but
“linspace”
.
.
.
Using matplotlib
You can Simply
Plotting cos(x)
• Without Numpy, you have to
Green color
and label
Position
of the
legend
Title
Set the
vertical limits
to be -1.5 to
1.5
Changing Markers/Line Style
Try it out
-- dashed
: dotted
-. dash dotted
- solid
o circle
< triangle_left
+ plus
Only affect
the most
recent graph
Multiple Figures
Position 9
If you really have a lot of figures
The following plotting will be in Figure 1
Number
of times
of >= 3
and < 4
Histogram
• Usually, histograms won’t have a bin for every
single number x
– 3 <= x < 4
• For example, if the data is the salary, every bin
will have a larger range
– 1000 <= x < 2000
– 2000 <= x < 3000
– etc.
Histogram
• Back to the dice example, say we want the
ranges:
– 3 <= x < 7
– 7< = x < 11
– 11<= x < 15
– 15 <= x < 19
• Then we need 4 bins
Application: Monopoly
• Is every place has a equal chance to be landed
on?
– NO!
Pie Chart
• How to FAQ
– https://matplotlib.org/faq/howto_faq.html
IT5001 Software Development
Fundamentals
16. Miscellaneous
1
Agenda
• Graph Problems
Route Problems
Shortest Distance
2
Decorators
• Decorator is a closure
Additionally, outer function accepts a function as input argument
• Example
3
Decorators - Example
4
Decorators: Example
5
Decorators: Example
6
Decorators: Applications
• Profiling
For timing functions
• Logging
For debugging
• Caching
For Memoization
7
Decorators for Caching
8
Fibonacci using decorators
9
Graphs
Path Between Vertices
10
Breadth-First Search
Objective:
B Checking if a path exists from
C
vertex A to vertex G
E
F
11
Graph Representation
A
• Consists of two components
Vertices
o A,B,C,D, E, …. B
Edges C
o (A,B), (A,C), (B,D)….
D
• How to represent it? E
Edge List F
o Contains list of all edges
Adjacency List/Dictionary G
o List of vertices that are adjacent to a given vertex
o Can use dictionary
• Provides mapping between each vertex and its neighbors
12
Edge List to Adjacency List
13
Breadth-First Search
14
Breadth-First Search
A
A
C B
E
F
G current ≠ destination
current 𝑛𝑛𝑛𝑛𝑛𝑛 𝑖𝑖𝑖𝑖 visited
visited = {}
frontier = [‘A’]
15
Breadth-First Search
A
A
B C D
C B
E
F
G current ≠ destination
current 𝑛𝑛𝑛𝑛𝑛𝑛 𝑖𝑖𝑖𝑖 visited
visited = {‘A’}
frontier = [‘B’, ‘C’, ’D’]
16
Breadth-First Search
A
A
B C D
C B
E
D
E
F
G current ≠ destination
current 𝑛𝑛𝑛𝑛𝑛𝑛 𝑖𝑖𝑖𝑖 visited
17
Breadth-First Search
A
A
B C D
C B
E F
D
E
F
G current ≠ destination
current 𝑛𝑛𝑛𝑛𝑛𝑛 𝑖𝑖𝑖𝑖 visited
18
Breadth-First Search
A
A
B C D
C B
E F G
D
E
F current 𝑛𝑛𝑛𝑛𝑛𝑛 𝑖𝑖𝑖𝑖 visited
G current ≠ destination
19
Breadth-First Search
A
A
B C D
C B
E F G
D
E
F
G current ≠ destination
current 𝑛𝑛𝑛𝑛𝑛𝑛 𝑖𝑖𝑖𝑖 visited
20
Breadth-First Search
A
A
B C D
C B
E F G
D
E
F
G current ≠ destination
current 𝑛𝑛𝑛𝑛𝑛𝑛 𝑖𝑖𝑖𝑖 visited
21
Breadth-First Search
A
A
B C D
C B
E F G
D
E
F
G
current == destination
Returns 𝑇𝑇𝑇𝑇𝑇𝑇𝑇𝑇
visited = {‘A’, ‘B’, ‘C’, ’D’, ‘E’}
frontier = [ ]
22
Depth-First Search
23
Depth-First Search
A
A
C B
E
F
G current ≠ destination
current 𝑛𝑛𝑛𝑛𝑛𝑛 𝑖𝑖𝑖𝑖 visited
visited = {}
frontier = [‘A’]
24
Depth-First Search
A
A
B C D
C B
E
F
G current ≠ destination
current 𝑛𝑛𝑛𝑛𝑛𝑛 𝑖𝑖𝑖𝑖 visited
visited = {‘A’}
frontier = [‘B’, ‘C’, ’D’]
25
Depth-First Search
A
A
B C D
C B
D
G
E
F
G current ≠ destination
current 𝑛𝑛𝑛𝑛𝑛𝑛 𝑖𝑖𝑖𝑖 visited
visited = {‘A’,’D’}
frontier = [‘B’, ‘C’, ’G’]
26
Depth-First Search
A
A
B C D
C B
D
G
E
F
G current == destination
Returns 𝑇𝑇𝑇𝑇𝑇𝑇𝑇𝑇
visited = {‘A’,’D’}
frontier = [‘B’, ‘C’, ’G’]
27
Weighted Graphs
• Objective:
Finding distance of shortest path between a source vertex and goal vertex
A
1
5
3 B
C
9 6
2 D
4
8 E
F
1 4
G
A
1
5
3 B
C
9 6
2 D
4
8 E
F
1 4
G
29
Algorithms
• Exhaustive Search
• Dijkstra’s Algorithm
30
Exhaustive Search
A
1 3
A 5
1 Search all possible routes
5 from A to G
B C D
3 B 8
C 9 6 4
2
9 6
2 D D E F F G
4 4 11
8 8 4 1 1
E
F
F G G G G
1 4
G 1 18 11 8
8
G
15
31
Recursive Algorithm
A
• Assumption 1
Shortest distance from neighbours of 𝐴𝐴 to 𝐺𝐺 is known 5
3 B
C
• Shortest distance from 𝐴𝐴 to 𝐺𝐺 is 9 6
min{𝑑𝑑 (𝐴𝐴, 𝑣𝑣) + 𝑑𝑑 𝑣𝑣, 𝐺𝐺 }, 𝑣𝑣 ∈ {𝐵𝐵, 𝐶𝐶, 𝐷𝐷} 2 D
4
8 E
Distance from 𝐴𝐴 Distance from
F
to its neighbour 𝑣𝑣 neighbour 𝑣𝑣 to 𝐺𝐺 4
1
G
32
Shortest Distance between Two Nodes
neighbours of vertex
33
Shortest Distance: Recursive Method
𝑑𝑑(𝐴𝐴, 𝐺𝐺)
A
1 3
5
B C D
𝑑𝑑(𝐵𝐵, 𝐺𝐺) 𝑑𝑑(𝐶𝐶, 𝐺𝐺) 𝑑𝑑(𝐷𝐷, 𝐺𝐺)
A
1
3
5
𝑑𝑑(𝐵𝐵, 𝐺𝐺)
B D
C 𝑑𝑑(𝐶𝐶, 𝐺𝐺) 𝑑𝑑(𝐷𝐷, 𝐺𝐺)
9 6
35
Shortest Distance: Recursive Method
A
1
3
5
𝑑𝑑(𝐵𝐵, 𝐺𝐺)
B D
C 𝑑𝑑(𝐶𝐶, 𝐺𝐺) 𝑑𝑑(𝐷𝐷, 𝐺𝐺)
9 6
𝑑𝑑(𝐷𝐷, 𝐺𝐺) D E
𝑑𝑑(𝐸𝐸, 𝐺𝐺)
4 8
𝑑𝑑(𝐹𝐹, 𝐺𝐺)
F G
𝑑𝑑(𝐺𝐺, 𝐺𝐺)
A
1
3
5
𝑑𝑑(𝐵𝐵, 𝐺𝐺)
B D
C 𝑑𝑑(𝐶𝐶, 𝐺𝐺) 𝑑𝑑(𝐷𝐷, 𝐺𝐺)
9 6
𝑑𝑑(𝐷𝐷, 𝐺𝐺) D E
𝑑𝑑(𝐸𝐸, 𝐺𝐺)
4 8
𝑑𝑑(𝐹𝐹, 𝐺𝐺)
F G
1 𝑑𝑑(𝐺𝐺, 𝐺𝐺)
𝑑𝑑 𝐴𝐴, 𝐺𝐺 = min{1 + 𝑑𝑑 𝐵𝐵, 𝐺𝐺 , 5 + 𝑑𝑑 𝐶𝐶, 𝐺𝐺 , 3 + 𝑑𝑑(𝐷𝐷, 𝐺𝐺)}
G 𝑑𝑑 𝐵𝐵, 𝐺𝐺 = min{9 + 𝑑𝑑 𝐷𝐷, 𝐺𝐺 , 6 + 𝑑𝑑 𝐸𝐸, 𝐺𝐺 }
𝑑𝑑(𝐺𝐺, 𝐺𝐺)
𝑑𝑑 𝐷𝐷, 𝐺𝐺 = min{4 + 𝑑𝑑 𝐹𝐹, 𝐺𝐺 , 8 + 𝑑𝑑 𝐺𝐺, 𝐺𝐺 }
𝑑𝑑 𝐹𝐹, 𝐺𝐺 = 1 + 𝑑𝑑 𝐺𝐺, 𝐺𝐺 37
Shortest Distance: Recursive Method
A
1 3
5
𝑑𝑑(𝐵𝐵, 𝐺𝐺)
B D
C 𝑑𝑑(𝐶𝐶, 𝐺𝐺) 𝑑𝑑(𝐷𝐷, 𝐺𝐺)
9 6
𝑑𝑑(𝐷𝐷, 𝐺𝐺) D E 𝑑𝑑(𝐸𝐸, 𝐺𝐺)
4 8 4
𝑑𝑑(𝐹𝐹, 𝐺𝐺)
F G G
11
1 𝑑𝑑(𝐺𝐺, 𝐺𝐺)
A
1 3
5
𝑑𝑑(𝐵𝐵, 𝐺𝐺)
B D
C 𝑑𝑑(𝐶𝐶, 𝐺𝐺) 𝑑𝑑(𝐷𝐷, 𝐺𝐺)
9 6
2
𝑑𝑑(𝐷𝐷, 𝐺𝐺) D E 𝑑𝑑(𝐸𝐸, 𝐺𝐺)
F
4 8 4
𝑑𝑑(𝐹𝐹, 𝐺𝐺)
F G G
11
1 𝑑𝑑(𝐺𝐺, 𝐺𝐺)
G
𝑑𝑑(𝐺𝐺, 𝐺𝐺)
𝑑𝑑 𝐴𝐴, 𝐺𝐺 = min{1 + 𝑑𝑑 𝐵𝐵, 𝐺𝐺 , 5 + 𝑑𝑑 𝐶𝐶, 𝐺𝐺 , 3 + 𝑑𝑑(𝐷𝐷, 𝐺𝐺)}
𝑑𝑑 𝐶𝐶, 𝐺𝐺 = 2 + 𝑑𝑑(𝐹𝐹, 𝐺𝐺)
39
Shortest Distance: Recursive Method
A
1 3
5
𝑑𝑑(𝐵𝐵, 𝐺𝐺)
B D
C 𝑑𝑑(𝐶𝐶, 𝐺𝐺) 𝑑𝑑(𝐷𝐷, 𝐺𝐺)
9 6
2
𝑑𝑑(𝐷𝐷, 𝐺𝐺) D E 𝑑𝑑(𝐸𝐸, 𝐺𝐺)
F
4 8 4
𝑑𝑑(𝐹𝐹, 𝐺𝐺) 1
F G G
G
11
1 𝑑𝑑(𝐺𝐺, 𝐺𝐺)
G
𝑑𝑑(𝐺𝐺, 𝐺𝐺) 𝑑𝑑 𝐴𝐴, 𝐺𝐺 = min{1 + 𝑑𝑑 𝐵𝐵, 𝐺𝐺 , 5 + 𝑑𝑑 𝐶𝐶, 𝐺𝐺 , 3 + 𝑑𝑑(𝐷𝐷, 𝐺𝐺)}
𝑑𝑑 𝐶𝐶, 𝐺𝐺 = 2 + 𝑑𝑑(𝐹𝐹, 𝐺𝐺)
𝑑𝑑 𝐹𝐹, 𝐺𝐺 = 1 + 𝑑𝑑(𝐺𝐺, 𝐺𝐺) 40
Shortest Distance: Recursive Method
A
1 3
5
𝑑𝑑(𝐵𝐵, 𝐺𝐺)
B
C 𝑑𝑑(𝐶𝐶, 𝐺𝐺) 𝑑𝑑(𝐷𝐷, 𝐺𝐺) D
9 6
2 8
𝑑𝑑(𝐹𝐹, 𝐺𝐺) 4
𝑑𝑑(𝐷𝐷, 𝐺𝐺) D E 𝑑𝑑(𝐸𝐸, 𝐺𝐺)
F F G
𝑑𝑑(𝐹𝐹, 𝐺𝐺) 4 8 4
1
1 𝑑𝑑(𝐺𝐺, 𝐺𝐺)
F G G
G G
11
1 𝑑𝑑(𝐺𝐺, 𝐺𝐺)
𝑑𝑑(𝐺𝐺, 𝐺𝐺)
G
𝑑𝑑 𝐴𝐴, 𝐺𝐺 = min{1 + 𝑑𝑑 𝐵𝐵, 𝐺𝐺 , 5 + 𝑑𝑑 𝐶𝐶, 𝐺𝐺 , 3 + 𝑑𝑑(𝐷𝐷, 𝐺𝐺)}
𝑑𝑑(𝐺𝐺, 𝐺𝐺)
41
Shortest Distance: Recursive Method
A
1 3
5
𝑑𝑑(𝐵𝐵, 𝐺𝐺)
B
C 𝑑𝑑(𝐶𝐶, 𝐺𝐺) 𝑑𝑑(𝐷𝐷, 𝐺𝐺) D
9 6
2 8
𝑑𝑑(𝐹𝐹, 𝐺𝐺) 4
𝑑𝑑(𝐷𝐷, 𝐺𝐺) D E 𝑑𝑑(𝐸𝐸, 𝐺𝐺)
F F G
𝑑𝑑(𝐹𝐹, 𝐺𝐺) 4 8 4
1
1 𝑑𝑑(𝐺𝐺, 𝐺𝐺)
F G G
G G
11
1 𝑑𝑑(𝐺𝐺, 𝐺𝐺)
𝑑𝑑(𝐺𝐺, 𝐺𝐺)
G
𝑑𝑑(𝐺𝐺, 𝐺𝐺)
42
Shortest Distance: Memoized Recursive Version
43
Summary
• Dynamic Programming
General Problem Solving
o Divide-and-conquer with redundant or overlapping subproblems
Optimization
o Solving problems that have overlapping subproblems with optimal solutions
o Subproblem dependency should be acyclic (i.e., only for DAGs)
44
Program Design
• Course project/FYP
Project Size at Work
Managing Complexity
Abstraction
• A technique to manage complexity
• Establishing a level of complexity on which a
person interacts with the system
• Suppressing the more complex details below
the current level.
How they work together?
?
Establish Level of Complexity
• The chief engineer want
to know
– How much fuel does the
propulsion engine uses
– How much force can the
engine provide
The level of complexity that the
?
Compare:
def hypotenuse(a, b):
return sqrt(sum_of_squares(a, b))
def square(x): ?
return x * x a
Versus: b
def hypotenuse(a, b):
return sqrt((a*a) + (b*b))
What Makes a Good
Abstraction?
1. Makes it more natural to think
about tasks and subtasks
Building Bricks
Floor/
story
Rooms
Bricks
1. Makes it more natural to think
about tasks and subtasks
Solution Primitives
Program
Functions
Primitives
def hypotenuse(a, b):
return sqrt(sum_of_squares(a, b))
def square(x):
return x * x
?
a
b
1. Makes it more natural to think
about tasks and subtasks
hypotenuse operators
sum_of_squares
square
operators
2. Makes programs easier to
understand
def hypotenuse(a, b):
return sqrt(sum_of_squares(a, b))
def square(x):
return x * x
3. Captures common patterns
• E.g. computing binomial coefficient
𝑛𝑛 𝑛𝑛!
=
𝑘𝑘 𝑘𝑘! 𝑛𝑛 − 𝑘𝑘 !
pi = 3.14159
def circle_area_from_radius(r):
return pi * square(r)
def circle_area_from_diameter(d):
return circle_area_from_radius(d/2)
5. Hides irrelevant details
• The structure of a gear box maybe interesting
to some fans but not everyone who drives
Made of?
How does it
work?
6. Separates specification from
implementation
• Specification: WHAT IT DOES
– E.g the function cos(x) compute the cosine of x
def square(x):
return x ** 2
def square(x):
return exp(double(log(x)))
def double(x): return x + x
7. Makes debugging (fixing errors)
easier
def hypotenuse(a, b):
return sqrt((a + a) * (b + b))
Where is/are
the bugs?
def hypotenuse(a,b):
return sqrt(sum_of_squares(a,b))
def square(x):
return x + x
Good Abstraction?
1. Makes it more natural to think about tasks
and subtasks
2. Makes programs easier to understand
3. Captures common patterns
4. Allows for code reuse
5. Hides irrelevant details
6. Separates specification from implementation
7. Makes debugging easier
Program Design
Top-down Approach
pretend you have whatever you need
Sequence of Writing
1 def hypotenuse(a, b):
return sqrt(sum_of_squares(a, b))
def square(x):
3
return x * x ?
a
pretend you have
whatever you need b
Another Example
• NTUC Comfort, the largest taxi operator in
Singapore, determines the taxi fare based on
distance traveled as follows:
Problem: Write a Python function
that computes the taxi fare from the
distance traveled.
How do we start?
Formulate the Problem
• We need a name!
– Pick a meaningful one
– Definitely not “foo”
Function
Formulate the Problem
• What are the
– Input?
– Output?
my_cool_package.py
Then I can use it for another file
• Another file: Same as the file name but
without “.py”
Or
• Another file:
Or
• Another file
Or But in general, it’s not a good
habit to name a
variable/function so short
• Another file that you cannot understand
what it does