Professional Documents
Culture Documents
Final Lesson
Final Lesson
Programming Fundamentals 1
Lesson 1
Pierre Kelsen
2017
1 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Outline
2 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
3 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
4 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
5 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Miller’s Law
The number of objects the average person can keep in working
memory is seven, plus or minus 2.
5 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Large numbers
1 million = 106 = 1.000.000
1 billion = 109 = 1.000.000.000
1 trillion = 1012 = 1.000.000.000.000
6 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Large numbers
1 million = 106 = 1.000.000
1 billion = 109 = 1.000.000.000
1 trillion = 1012 = 1.000.000.000.000
6 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
7 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
8 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
8 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
9 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
10 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
11 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
12 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
13 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
14 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Discussion
Why does the algorithm described on the previous slide not
constitute a program? What is missing?
15 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Discussion
Why does the algorithm described on the previous slide not
constitute a program? What is missing?
Answer
The algorithm was formulated in English.
A program must be formulated in a language the computer
understands.
15 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
16 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
17 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
18 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
19 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
20 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Church-Turing Thesis
If a problem is computable (that
is, solvable by a computer), then
a Turing Machine can be
programmed to compute it.
21 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Question
Can every problem be computed?
22 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Question
Can every problem be computed?
Answer
No. Example of a non-computable problem: Halting Problem
I Input: Program P (as string), input for Program P
I Output: Yes, if P halts on input of P, No, otherwise.
22 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
23 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Question
Does this mean that we need to use machine code to program
computers?
24 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Question
Does this mean that we need to use machine code to program
computers?
Answer
I Fortunately NOT.
I Can use programming languages that use a higher level of
abstraction, closer to our natural language
I There exist special programs that translate these high-level
programs to machine code.
I These programs are called compilers.
24 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Question
Which programming language(s) do you know?
25 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
26 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
27 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
28 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
29 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
30 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
31 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Question
So what is the simplest Python program?
32 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Question
So what is the simplest Python program?
Answer
The empty program = empty sequence of statements.
Not a very useful one!
32 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
33 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
34 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
35 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
36 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
37 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
38 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
39 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
40 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
40 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
41 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Question
Which of the following two code snippets is easier to understand,
and why?
x1 = 3.14 pi = 3.14
x2 = 13.1 diameter = 13.1
c = x1*(x2**2) area = pi*(diameter**2)
42 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
43 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Exercise
Enter the assignments similar to those given on slide 42. After
each assignment check the id (or ”location” or ”address”) of the
variable and its type using the functions id() and type().
I DEMO
44 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
45 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
46 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
47 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
48 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
49 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
50 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
51 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
52 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Exercise
Enter expressions similar to those given above into the Python
shell and observe their result
I DEMO
53 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Example
x += y is equivalent to: x = x + y
x *= y is equivalent to: x = x * y
54 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
55 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
56 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
57 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
58 / 59
About This Course Towards Computational Problem Solving From Problems to Programs The Python Programming Language
Example
str(3) # converts int to string
bool(2) # converts integer to boolean
DEMO
59 / 59
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Programming Fundamentals 1
Lesson 2
Pierre Kelsen
2017
1 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Outline
2 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Discussion
Can you describe in your own words the syntax of this program?
3 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Discussion
Can you describe, as an analogy, some syntactic rules of English?
4 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Question
Is the Python syntax enough to define the Python language?
5 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Question
Is the Python syntax enough to define the Python language?
Answer
No. We also need to define the meaning of Python programs.
Discussion
How would you define the meaning of a Python program?
5 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
6 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
6 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
7 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
8 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
9 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
if x < 0: print('x is negative')
10 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
if x < 0: print('x is negative')
Most Python programmers prefer to put the statement on a
separate line:
if x < 0:
print('x is negative')
Note: indentation is mandatory!!! (see slide below)
10 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
11 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
12 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
if x < 0:
print('x is negative')
elif x%2:
print('x is positive and odd')
else
print('x is non-negative and even')
13 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Programming Advice
Python Coding Conventions
1
https://www.python.org/dev/peps/pep-0008/
14 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
15 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
x = 512
print('value of x is ', x)
count = 0
while x > 1:
x //= 2 # floor division
count += 1 # current block ends here
print('The approximate log2 is', count)
16 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
17 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
I Request a number n from the user and return the sum of the
squares of numbers from 0 to n
18 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
19 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
20 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
21 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
'A3B'.lower() #returns: 'a3b'\\
'A3B'.startswith('A3') #returns: True\\
'A3B'.endswith('A3') #returns: False
DEMO!
22 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
2
abbreviation of ”id est” (Latin), meaning: ”that is”
23 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
2
abbreviation of ”id est” (Latin), meaning: ”that is”
23 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
24 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
'Hello ' + 'world' #'Hello world'
3*'4' #'444'
25 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
'Hello ' + 'world' #'Hello world'
3*'4' #'444'
25 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
'Hello' in 'Hello world' #True
'' in 'abc' #True
'z' in 'xy' #False
'Hello'.index('l') #2
26 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
'Hello world'[0] #'H'
'xyz'[2] #'z'
27 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
'Hello world'[0:5] #'Hello'
'Hello world'[5:] #' world'
'Hello world'[:5] #'Hello'
28 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
['2','1a','3b'] #list with 3 strings
[3,1] #list with two numbers
[] #empty list
29 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
I The list type being a sequence type we can use all operations
(as well as the len function) defined above on string examples
Example
len(['2','1a','3b']) # 3
[1] + [2,3] # [1,2,3]
[5,4,'7a'][1:] # [4,'7a']
30 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
'Hello world'.split() #['Hello','world']
'23 1 78'.split() #['23','1','78']
31 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
32 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
33 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
34 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
35 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Question
Why is it clear that the previous program (both versions)
terminates?
36 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Question
Why is it clear that the previous program (both versions)
terminates?
Answer
Because the for-loop is executed at most once for each number in
the numberList sequence.
36 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Discussion
Do you see a more efficient (faster) method to solve this problem?
37 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
3
https://en.wikipedia.org/wiki/Binary search algorithm
38 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
39 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
40 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
41 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
42 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
43 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
43 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Definition
A middle element is an element in a sequence such that at most
half of the elements are on each side of the middle element.
Example
For [2, 4, 8] we want at most 3/2, i.e., at most one element on
either side , so the only choice is 4
For [3, 5, 7, 9] we want at most 4/2, i.e., at most two elements on
either side , so the possible choices are 5 or 7.
43 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
I More generally:
I if a sequence has odd length 2k + 1 the middle element is
element at position k (first index = 0)
I if a sequence has even length 2k the middle element is element
at position k − 1 or k
I Guess expression for middle element: (a + b)//2
I Check this:
I if a sequence has odd length then b = a + 2k and
(a + b)//2 = (2a + 2k)//2 = a + k (satisfying above
condition)
I if a sequence has even length 2k, then b = a + 2k − 1 and
(a + b)//2 = (2a + 2k − 1)//2 = a + k − 1 (satisfying above
condition)
44 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
46 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Discussion
Can anybody explain why the loop in Version 3 should terminate?
46 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
47 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
while a<=b:
m= (a+b)//2
if n==numberList[m]:
print('Number at position: ',m)
break
elif n<numberList[m]:
b = m-1
else:
a = m+1
48 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
49 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Discussion
How can we argue that the program for binary search is correct?
50 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
51 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
while a<=b:
m= a+(b-a+1)//2
if n==numberList[m]:
print('Number at position: ',m)
break
elif n<numberList[m]:
b = m-1
else:
a = m+1
52 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
53 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
53 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
53 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
53 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
53 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
54 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
55 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
55 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
56 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Question
What is the complexity of linear search in the best case?
57 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Question
What is the complexity of linear search in the best case?
Answer
I In the best case the element is found at the first position of
the sequence
I Thus the complexity in the best case is independent of the
length of the input sequence
I We talk about constant complexity
57 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
58 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
59 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
59 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
60 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
60 / 61
Syntax and Semantics Control Flow Statements Strings and Sequences Two Simple Problems
Example
n=2 log n = 1
n=1024 log n = 10
n=1048576 log n = 20
n=1073741824 log n = 30
4
”vs” stands for ”versus” or ”compared to”
61 / 61
Towards Functions Functions in Python
Programming Fundamentals 1
Lesson 3
Pierre Kelsen
2017
1 / 55
Towards Functions Functions in Python
Outline
Towards Functions
Functions in Python
2 / 55
Towards Functions Functions in Python
Towards Functions
Code Reuse
3 / 55
Towards Functions Functions in Python
Towards Functions
Structure of Program 2
# Program 2
# some statements
# code for Number Search
Towards Functions
Problems with Copy and Paste
Question
What are drawbacks of this approach to code reuse?
5 / 55
Towards Functions Functions in Python
Towards Functions
Problems with Copy and Paste
Question
What are drawbacks of this approach to code reuse?
Answer
Any modification to the method used for number search will entail
changes in multiple places
5 / 55
Towards Functions Functions in Python
Towards Functions
Problems with Copy and Paste
Question
What are drawbacks of this approach to code reuse?
Answer
Any modification to the method used for number search will entail
changes in multiple places
Discussion
Why is this really a problem? Imagine real world scenarios.
5 / 55
Towards Functions Functions in Python
Towards Functions
Programming Advice
Rule
Say each thing only once in one place!
6 / 55
Towards Functions Functions in Python
Towards Functions
Programming Advice
Rule
Say each thing only once in one place!
Discussion
Why does the ”copy and paste” approach to code reuse violate
this rule?
6 / 55
Towards Functions Functions in Python
Towards Functions
How to Reuse
Question
So how can we reuse code without reproducing it?
7 / 55
Towards Functions Functions in Python
Towards Functions
How to Reuse
Question
So how can we reuse code without reproducing it?
Answer
By packaging the code as a function.
7 / 55
Towards Functions Functions in Python
Towards Functions
Functions in Mathematics
Definition (function)1
In mathematics, a function is a relation between a set of inputs
and a set of permissible outputs with the property that each input
is related to exactly one output.
1
https://en.wikipedia.org/wiki/Function (mathematics)
8 / 55
Towards Functions Functions in Python
Towards Functions
From Programs to Functions
Question
What is missing for a program to be a full-fledged function?
9 / 55
Towards Functions Functions in Python
Towards Functions
From Programs to Functions
Question
What is missing for a program to be a full-fledged function?
Answer
We need to clearly identify inputs and outputs.
9 / 55
Towards Functions Functions in Python
Functions in Python
Example of a Function in Python
2
There is a builtin function min, hence we choose a different name
10 / 55
Towards Functions Functions in Python
Functions in Python
General Form
11 / 55
Towards Functions Functions in Python
Functions in Python
General Form
11 / 55
Towards Functions Functions in Python
Functions in Python
Function Call
Example
myMin(3, 4) calls function myMin with arguments 3 and 4
Parameter x will be bound to 3, and parameter y will be bound to 4
12 / 55
Towards Functions Functions in Python
Functions in Python
Return value
13 / 55
Towards Functions Functions in Python
Functions in Python
Return value
13 / 55
Towards Functions Functions in Python
Functions in Python
Return value
13 / 55
Towards Functions Functions in Python
Functions in Python
Function Call Execution
14 / 55
Towards Functions Functions in Python
Functions in Python
Positional Parameter Binding
Example
The call myMin(3,4) can be replaced by myMin(x=3,y=4) or even
myMin(y=4,x=3). These calls are all equivalent.
The call myMin(x=3, 4) is not allowed (see last item above).
15 / 55
Towards Functions Functions in Python
Functions in Python
Optional Parameters
Example
In the function definition
def sortList(numberList, ascending = True):
the second parameter has a default value.
The call sortList(list) is equivalent to sortList(list,
True)
16 / 55
Towards Functions Functions in Python
Functions in Python
Optional Parameters - Continued
17 / 55
Towards Functions Functions in Python
Functions in Python
To Return or Not to Return
Example
def meaningOfLife():
print('Not sure what it is')
is a valid function definition
18 / 55
Towards Functions Functions in Python
Functions in Python
None as a Return Value
Question
In the cases outlined in the second atom on the previous slide
(including the example), does the function have a return value?
19 / 55
Towards Functions Functions in Python
Functions in Python
None as a Return Value
Question
In the cases outlined in the second atom on the previous slide
(including the example), does the function have a return value?
Answer
Yes, it has! In those case the function returns None.
19 / 55
Towards Functions Functions in Python
Functions in Python
None
Question
Recall the function
def meaningOfLife():
print('Not sure what it is')
print(meaningOfLife()==None)
What is the output? → DEMO
20 / 55
Towards Functions Functions in Python
Functions in Python
What is None? - continued
Question
What is the type of None? How can you find this out?
21 / 55
Towards Functions Functions in Python
Functions in Python
What is None? - continued
Question
What is the type of None? How can you find this out?
→ DEMO
21 / 55
Towards Functions Functions in Python
Functions in Python
What is None? - continued
Question
What is the type of None? How can you find this out?
→ DEMO
Answer
The type of None is NoneType. None is the only value of
NoneType.
21 / 55
Towards Functions Functions in Python
Functions in Python
Local Variable
Example
In the following function, y is a local variable
def f(x):
print(x)
y=1
print(x+y)
22 / 55
Towards Functions Functions in Python
Functions in Python
Global versus Local Variables
Example
Consider the following program:
def f(x):
y=1
print(y)
y=3
f(y)
print(y)
Question
What is the output?
23 / 55
Towards Functions Functions in Python
Functions in Python
Global versus Local Variables
Example
Consider the following program:
def f(x):
y=1
print(y)
y=3
f(y)
print(y)
Question Answer
1
What is the output?
3
23 / 55
Towards Functions Functions in Python
Functions in Python
Global versus Local Variables - Continued
24 / 55
Towards Functions Functions in Python
Functions in Python
Lifetime of Variables
I Global variables exist as long as the program has not
terminated
I Local variables are created every time the function is executed
and removed when the function ends
I When the example program executes we have the following
situation
25 / 55
Towards Functions Functions in Python
Functions in Python
Meaning of Variable Names
26 / 55
Towards Functions Functions in Python
Functions in Python
Meaning of Variable Names
26 / 55
Towards Functions Functions in Python
Functions in Python
Meaning of Variable Names
26 / 55
Towards Functions Functions in Python
Functions in Python
Referencing Global Variables
27 / 55
Towards Functions Functions in Python
Functions in Python
Referencing Global Variables
27 / 55
Towards Functions Functions in Python
Functions in Python
Referencing Global Variables
27 / 55
Towards Functions Functions in Python
Functions in Python
Referencing Global Variables - Continued
Question
Is it a good idea to access global variables from inside a function?
28 / 55
Towards Functions Functions in Python
Functions in Python
Referencing Global Variables - Continued
Question
Is it a good idea to access global variables from inside a function?
Answer
No, it’s not a good idea because ...
28 / 55
Towards Functions Functions in Python
Functions in Python
Referencing Global Variables - Continued
Question
Is it a good idea to access global variables from inside a function?
Answer
No, it’s not a good idea because ...
I ... it makes programs more difficult to read
28 / 55
Towards Functions Functions in Python
Functions in Python
Referencing Global Variables - Continued
Question
Is it a good idea to access global variables from inside a function?
Answer
No, it’s not a good idea because ...
I ... it makes programs more difficult to read
I ... it makes functions more difficult to reuse
28 / 55
Towards Functions Functions in Python
Functions in Python
Programming Advice
Advice
It is generally not a good idea to reference global variables from a
function. If the function needs to access information at the global
level, this information should be passed via parameters.
29 / 55
Towards Functions Functions in Python
Functions in Python
Applying the Advice
# BEFORE
def f():
print(y)
y=3
f()
print(y)
30 / 55
Towards Functions Functions in Python
Functions in Python
Applying the Advice
# BEFORE # AFTER
def f(): def f(z):
print(y) print(z)
y=3 y=3
f() f(y)
print(y) print(y)
30 / 55
Towards Functions Functions in Python
Functions in Python
Alternative
# BEFORE
def f():
print(y)
y=3
f()
print(y)
31 / 55
Towards Functions Functions in Python
Functions in Python
Alternative
# BEFORE # AFTER
def f(): def f(y):
print(y) print(y)
y=3 y=3
f() f(y)
print(y) print(y)
31 / 55
Towards Functions Functions in Python
Functions in Python
Programming Advice
Advice
It is recommended to give parameters names different from those
of global variables to avoid confusion and enhance readability.
32 / 55
Towards Functions Functions in Python
Functions in Python
A Simple Function
def sumOfSquares(n):
""" Assumes n is an integer with n>=0
Returns the sum of squares of numbers form 0 to n """
s = 0
for i in range(n+1):
s += i * i
return s
Question
What do you notice about this function?
33 / 55
Towards Functions Functions in Python
Functions in Python
Docstrings
I The function of squares contains a special comment
(multi-line!) enclosed by triple quotes (watch the indent!)
""" Assumes n is an integer with n>=0
Returns the sum of squares of numbers from 0 to n """
Question
What is the purpose of this particular comment?
34 / 55
Towards Functions Functions in Python
Functions in Python
Docstrings
I The function of squares contains a special comment
(multi-line!) enclosed by triple quotes (watch the indent!)
""" Assumes n is an integer with n>=0
Returns the sum of squares of numbers from 0 to n """
Question
What is the purpose of this particular comment?
Answer
To define the contract between the user of the function and the
implementer (programmer). We also talk about the specification of
a function
34 / 55
Towards Functions Functions in Python
Functions in Python
Functions and Contracts
Discussion
Can you think of analogies in the real world?
35 / 55
Towards Functions Functions in Python
Functions in Python
Assumptions
Question
What happens when an assumption is violated?
36 / 55
Towards Functions Functions in Python
Functions in Python
Assumptions
Question
What happens when an assumption is violated?
Answer
Errors or other unpredictable behavior may occur.
36 / 55
Towards Functions Functions in Python
Functions in Python
Violating an Assumption
def sumOfSquares(n):
""" Assumes n is an integer with n>=0
Returns the sum of squares of numbers from 0 to n """
s = 0
for i in range(n+1):
s += i*i
return s
Question
Can you explain the observed behavior?
37 / 55
Towards Functions Functions in Python
Functions in Python
Benefits of contracts
Question
Who benefits from the use of contracts?
38 / 55
Towards Functions Functions in Python
Functions in Python
Benefits of contracts
Question
Who benefits from the use of contracts?
Answer
I The programmer because he knows what he must implement.
38 / 55
Towards Functions Functions in Python
Functions in Python
Benefits of contracts
Question
Who benefits from the use of contracts?
Answer
I The programmer because he knows what he must implement.
I The client of the function because ideally the contract is
enough to understand what the function does
38 / 55
Towards Functions Functions in Python
Functions in Python
Information Hiding
Question
Why is this use of information hiding useful?
39 / 55
Towards Functions Functions in Python
Functions in Python
Information Hiding
Question
Why is this use of information hiding useful?
Answer
It shields the client from the complexity of the implementation.
39 / 55
Towards Functions Functions in Python
Functions in Python
Viewing docstrings
40 / 55
Towards Functions Functions in Python
Modules
Software Complexity
Discussion
Why is software complexity a problem?
41 / 55
Towards Functions Functions in Python
Modules
Definition of Modules
42 / 55
Towards Functions Functions in Python
Modules
Benefits of Modules
43 / 55
Towards Functions Functions in Python
Modules
Benefits of Modules
43 / 55
Towards Functions Functions in Python
Modules
Benefits of Modules
43 / 55
Towards Functions Functions in Python
Modules
Benefits of Modules
43 / 55
Towards Functions Functions in Python
Modules
Module Example
I Example of a module circle.py
pi = 3.14159
def area(radius):
return pi*(radius**2)
def circumference(radius):
return 2*pi*radius
def sphereSurface(radius):
return 4.0*area(radius)
def sphereVolume(radius):
return (4.0/3.0)*pi*(radius**3)
44 / 55
Towards Functions Functions in Python
Modules
Modules and Namespaces
45 / 55
Towards Functions Functions in Python
Modules
Modules and Namespaces - Example
Example
I Suppose we have two implementations of a circle module
called circle1 and circle2 with the same function and variable
names
I We could then test values of pi constants as follows:
46 / 55
Towards Functions Functions in Python
Modules
Other Forms of Import
Example
I We can also import using the following syntax:
from <moduleName> import <something>
I Here <something> can either be
I a list of identifiers, e.g., func1, func2
I a single renamed identifier, e.g.,
from <moduleName> import f1 as func
I an asterisk, as in: from circle import *
47 / 55
Towards Functions Functions in Python
Modules
Other Forms of Import (2)
Caveat3
If there is a name clash between an imported identifier and a local
identifier, the imported identifier will be masked (or hidden).
The form with the asterisk makes name clashes more likely.
3
”caveat” is a synonym for ”warning”
48 / 55
Towards Functions Functions in Python
Modules
Programming Advice
Advice
With the from-import mechanism, name clashes become
possible. Because of this, import <moduleName> is the preferred
form of import in Python.
49 / 55
Towards Functions Functions in Python
Modules
Main Module
50 / 55
Towards Functions Functions in Python
Modules
Viewing the Namespace
51 / 55
Towards Functions Functions in Python
Modules
Loading Modules
import sys
sys.path
52 / 55
Towards Functions Functions in Python
Modules
Information Hiding with Modules
53 / 55
Towards Functions Functions in Python
Modules
Three Namespaces
54 / 55
Towards Functions Functions in Python
Modules
Masking of Identifiers
Example
I When a function f executes with a local variable y, and a
variable with that name exists in the global namespace, the
local variable masks the global one (see slide 25)
I When a module is imported using
from <moduleName> import * and that module defines a
function of the same name as a builtin function, the imported
name masks the builtin function.
55 / 55
Problem Solving Recursion
Programming Fundamentals 1
Lesson 4
Pierre Kelsen
2017
1 / 58
Problem Solving Recursion
Outline
Problem Solving
Recursion
2 / 58
Problem Solving Recursion
Problem Solving
Reducing Complexity
3 / 58
Problem Solving Recursion
Problem Solving
Reducing Complexity
3 / 58
Problem Solving Recursion
Problem Solving
Top-Down Approach
4 / 58
Problem Solving Recursion
Problem Solving
Top-Down Approach
Example
I The Number Search Problem can be decomposed as follows:
I Subproblem 1: obtain input
I Subproblem 2: compute result
I Subproblem 3: output result
5 / 58
Problem Solving Recursion
Problem Solving
Top-Down Approach - Example
6 / 58
Problem Solving Recursion
Problem Solving
Bottom-up Approach
7 / 58
Problem Solving Recursion
Problem Solving
Bottom-up Approach
8 / 58
Problem Solving Recursion
Problem Solving
Top-down or Bottom-up Approach
Question
So which one should we use – top-down or bottom-up?
9 / 58
Problem Solving Recursion
Problem Solving
Top-down or Bottom-up Approach
Question
So which one should we use – top-down or bottom-up?
Answer
In practice both approaches are often used together: one does
decompose the problem down to some level and then use existing
solutions (eg., existing functions) for solving some subproblems
9 / 58
Problem Solving Recursion
Problem Solving
Bottom-up Approach
Question
Can you think of examples of top-down and bottom-up approaches
for solving problems in the real world?
10 / 58
Problem Solving Recursion
Problem Solving
An Interesting Special Case
11 / 58
Problem Solving Recursion
Recursion
Recursion in Real Life
1 2
1
https://upload.wikimedia.org/wikipedia/en/c/c1/Vache qui rit.png
2
https://en.wikipedia.org/wiki/File:Russian-Matroshka.jpg
12 / 58
Problem Solving Recursion
Recursion
Factorial Function
5! = 5 × 4 × 3 × 2 × 1 = 120
Question
What is the practical significance of the factorial function?
3
https://en.wikipedia.org/wiki/Factorial
13 / 58
Problem Solving Recursion
Recursion
Factorial Function
5! = 5 × 4 × 3 × 2 × 1 = 120
Question
What is the practical significance of the factorial function?
Answer
n! represents the number of orderings (also called ”permutations”)
of n elements
3
https://en.wikipedia.org/wiki/Factorial
13 / 58
Problem Solving Recursion
Recursion
Factorial Function in Python
14 / 58
Problem Solving Recursion
Recursion
Factorial Function
1! = 1
(n + 1)! = (n + 1) · n!
I In functional notation:
f (1) = 1
f (n + 1) = (n + 1) · f (n)
15 / 58
Problem Solving Recursion
Recursion
Factorial Function
Question
Why do we need the base case?
16 / 58
Problem Solving Recursion
Recursion
Factorial Function
Question
Why do we need the base case?
Answer
To avoid infinite recursive descent
16 / 58
Problem Solving Recursion
Recursion
Recursive Program for Factorial
17 / 58
Problem Solving Recursion
Recursion
Recursive Program for Factorial
17 / 58
Problem Solving Recursion
Recursion
Recursive Program for Factorial
18 / 58
Problem Solving Recursion
Recursion
Functions calling Functions
Example
I The call chain for f(4)
19 / 58
Problem Solving Recursion
Recursion
Activation Records
I Each function call is associated with an activation record
I An activation record contains the names and values of all
parameters and local variables; it also contains the place from
where the function was called (omitted in figure below)
I The data in the activation record is required for the function
call to be correctly executed (Why?)
Example
I Call chain with activation records
20 / 58
Problem Solving Recursion
Recursion
Managing the Activation Records
21 / 58
Problem Solving Recursion
Recursion
Visualization of Nested Calls
22 / 58
Problem Solving Recursion
Recursion
Stack
23 / 58
Problem Solving Recursion
Recursion
Nested Calls with Stack
Circled numbers indicate order in which stack operations are called. Each
push/pop corresponds to the function call above it
24 / 58
Problem Solving Recursion
Recursion
Common Uses of Stacks
4 5
4
https://https://pixabay.com/p-2630076/?no redirect
5
https://static.pexels.com/photos/9415/food-lunch-kitchen-eat.jpg
25 / 58
Problem Solving Recursion
Recursion
Recursion Depth
26 / 58
Problem Solving Recursion
Recursion
Recursion Depth
26 / 58
Problem Solving Recursion
Recursion
Iterative Solution
27 / 58
Problem Solving Recursion
Recursion
Iterative Solution
def f(n):
""" Assumes that n is an integer >0
Returns n! """
result = 1
for i in range(2, n+1): # from 2 to n
result *= i
return result
27 / 58
Problem Solving Recursion
Recursion
Recursive vs Iterative Solution
6
”vs” stands for ”versus”, meaning ”compared to”
28 / 58
Problem Solving Recursion
Recursion
Recursive vs Iterative Solution
6
”vs” stands for ”versus”, meaning ”compared to”
28 / 58
Problem Solving Recursion
Recursion
Fibonacci Numbers
Question
Who has heard about Fibonacci numbers?
7
https://en.wikipedia.org/wiki/Fibonacci number
29 / 58
Problem Solving Recursion
Recursion
Fibonacci Numbers
Question
Who has heard about Fibonacci numbers?
Definition7
In mathematics, the Fibonacci numbers are the numbers in the
following integer sequence, called the Fibonacci sequence, and are
characterized by the fact that every number after the first two is
the sum of the two preceding ones:
7
https://en.wikipedia.org/wiki/Fibonacci number
29 / 58
Problem Solving Recursion
Recursion
Fibonacci Numbers: Recursive Definition
F1 = 1
F2 = 1
Fn = Fn−1 + Fn−2 for n > 2
I This straightforward recursive definition leads to a
straightforward recursive implementation (next slide)
30 / 58
Problem Solving Recursion
Recursion
Fibonacci Numbers: Recursive Implementation
def fib(n):
""" Assumes that n is an integer >0
Returns nth Fibonacci number """
if n == 1:
return 1
elif n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
31 / 58
Problem Solving Recursion
Recursion
Testing the Recursive Program
32 / 58
Problem Solving Recursion
Recursion
Testing the Recursive Program
32 / 58
Problem Solving Recursion
Recursion
From Call Chain to Call Tree
Question
Can the calls resulting from executing fib(n) still be represented by
a call chain?
33 / 58
Problem Solving Recursion
Recursion
From Call Chain to Call Tree
Question
Can the calls resulting from executing fib(n) still be represented by
a call chain?
Answer
No, calling fib(n) will result in a call tree.
33 / 58
Problem Solving Recursion
Recursion
Call Tree for fib(5)
Question
Complexity of fib(n)?
34 / 58
Problem Solving Recursion
Recursion
Complexity
35 / 58
Problem Solving Recursion
Recursion
Iterative Solution
def fib(n):
""" Assumes that n is an integer >0
Returns nth Fibonacci number """
if n == 1:
return 1
elif n == 2:
return 1
else:
last = 1
secondToLast = 1
for i in range(3, n+1): # i.e., from 3 to n
last, secondToLast = last + secondToLast, last
return last
36 / 58
Problem Solving Recursion
Recursion
Complexity of Iterative Solution
I What is the complexity of the iterative solution?
37 / 58
Problem Solving Recursion
Recursion
Complexity of Iterative Solution
I What is the complexity of the iterative solution?
I The time taken is roughly proportional to n
I We say that the complexity is roughly a linear function of n
I Complexity of recursive solution is roughly exponential in n
I Thus, for Fibonacci numbers the iterative solution is much
preferred!
37 / 58
Problem Solving Recursion
Recursion
Another Problem
38 / 58
Problem Solving Recursion
Recursion
Problem Definition
Question
What is this problem called?
39 / 58
Problem Solving Recursion
Recursion
Problem Definition
Question
What is this problem called?
Answer
The Tower of Hanoi problem
39 / 58
Problem Solving Recursion
Recursion
Solution for n=4
40 / 58
Problem Solving Recursion
Recursion
Solution for n=4
40 / 58
Problem Solving Recursion
Recursion
Some observations
41 / 58
Problem Solving Recursion
Recursion
Some observations (2)
I After moving the largest disk from the leftmost peg to the
rightmost peg, it would suffice to move the remaining disks
from the middle peg to the rightmost peg
I This suggests the following method to solve the problem
I move all the disks but the largest one from the leftmost peg to
the middle one
I move the largest disk to the rightmost one
I move the other disks from the middle to the rightmost peg
Question
Is this a divide and conquer approach, i.e., are the subproblems of
the same type as the initial problem?
42 / 58
Problem Solving Recursion
Recursion
Towards divide an conquer
Attempt 1
The Tower of Hanoi problem consists in moving n disks from the
leftmost peg to the rightmost peg without ever placing a larger
disk on a smaller disk
Question
Does this definition lead to a divide and conquer approach?
43 / 58
Problem Solving Recursion
Recursion
A general definition
44 / 58
Problem Solving Recursion
Recursion
A general definition
Attempt 2
The Tower of Hanoi problem consists in moving n disks from a
source peg to a target peg without ever placing a larger disk on a
smaller disk
44 / 58
Problem Solving Recursion
Recursion
A more formal definition
45 / 58
Problem Solving Recursion
Recursion
A more formal definition
45 / 58
Problem Solving Recursion
Recursion
A more formal definition
46 / 58
Problem Solving Recursion
Recursion
A recurrence relation
8
+ denotes sequence concatenation
47 / 58
Problem Solving Recursion
Recursion
Python Implementation
def t(n,i,j,k):
''' Assume n is an integer >= 0
Assume that {i,j,k} = {1,2,3}
Return the sequence of moves to move the n top disks
from peg i to peg j while using peg k as auxiliary peg'''
if n == 0:
return []
else:
return t(n-1,i,k,j) +[[i,j]] + t(n-1,k,j,i)
48 / 58
Problem Solving Recursion
Recursion
Question about the Implementation
Question
Why do we write [[i,j]]9 for the move (i,j) and not simply [i,j]?
9
Recall that elements surrounded by brackets denote a list (see lesson 2)
49 / 58
Problem Solving Recursion
Recursion
Question about the Implementation
Question
Why do we write [[i,j]]9 for the move (i,j) and not simply [i,j]?
Answer
Since otherwise we lose the structure of the sequence of moves as
a sequence of pairs, i.e., the function simply outputs a sequence of
numbers.
DEMO
9
Recall that elements surrounded by brackets denote a list (see lesson 2)
49 / 58
Problem Solving Recursion
Recursion
Testing the Python Implementation
50 / 58
Problem Solving Recursion
Recursion
Testing the Python Implementation
50 / 58
Problem Solving Recursion
Recursion
Call Tree for Towers of Hanoi
I Since there are two recursive calls, we get a call tree rather
than a call chain
I Here is the call tree for 3 disks:
51 / 58
Problem Solving Recursion
Recursion
About that Call Tree (2)
Question
What does the call tree for the t-function have in common with
the call tree for the Fibonacci function?
52 / 58
Problem Solving Recursion
Recursion
About that Call Tree (2)
Question
What does the call tree for the t-function have in common with
the call tree for the Fibonacci function?
Answer
They both contain redundant computations, i.e., multiple
computations of the same subproblem.
Can you give examples?
52 / 58
Problem Solving Recursion
Recursion
About that Call Tree (3)
Question
Does the previous observation imply that the t-function has high
complexity? What do you think?
53 / 58
Problem Solving Recursion
Recursion
About that Call Tree (3)
Question
Does the previous observation imply that the t-function has high
complexity? What do you think?
Answer
In fact NOT. To understand why let us take a closer look at the
moves produced by t.
53 / 58
Problem Solving Recursion
Recursion
Moves in the call tree
54 / 58
Problem Solving Recursion
Recursion
Call Tree With Moves
Question
What can we say about the number of moves (= number of black
dots)?
55 / 58
Problem Solving Recursion
Recursion
Tree terminology
Example
Root node:
56 / 58
Problem Solving Recursion
Recursion
Tree terminology
Example
Root node: a
56 / 58
Problem Solving Recursion
Recursion
Tree terminology
Example
Root node: a
Children of c:
56 / 58
Problem Solving Recursion
Recursion
Tree terminology
Example
Root node: a
Children of c: d, e
56 / 58
Problem Solving Recursion
Recursion
Tree terminology
Example
Root node: a
Children of c: d, e
Parent of c:
56 / 58
Problem Solving Recursion
Recursion
Tree terminology
Example
Root node: a
Children of c: d, e
Parent of c: a
56 / 58
Problem Solving Recursion
Recursion
Tree terminology
Example
Root node: a
Children of c: d, e
Parent of c: a
Internal nodes:
56 / 58
Problem Solving Recursion
Recursion
Tree terminology
Example
Root node: a
Children of c: d, e
Parent of c: a
Internal nodes: a, c
56 / 58
Problem Solving Recursion
Recursion
Tree terminology
Example
Root node: a
Children of c: d, e
Parent of c: a
Internal nodes: a, c
Leaf nodes:
56 / 58
Problem Solving Recursion
Recursion
Tree terminology
Example
Root node: a
Children of c: d, e
Parent of c: a
Internal nodes: a, c
Leaf nodes: b, d, e
56 / 58
Problem Solving Recursion
Recursion
Call Tree With Moves (2)
Answer
The number of moves is equal to the number of internal nodes of
the tree.
How many internal nodes are there?
57 / 58
Problem Solving Recursion
Recursion
Call Tree With Moves (2)
Answer
The number of moves is equal to the number of internal nodes of
the tree.
How many internal nodes are there? 7
Question
How does the total number of nodes in the call tree compare to
the number of internal nodes?
57 / 58
Problem Solving Recursion
Recursion
Call Tree With Moves (2)
Answer
The number of moves is equal to the number of internal nodes of
the tree.
How many internal nodes are there? 7
Question
How does the total number of nodes in the call tree compare to
the number of internal nodes?
Answer
We claim that the total number of nodes is at most three times
the number of internal nodes. Why?
57 / 58
Problem Solving Recursion
Recursion
Number of Nodes in the Call Tree
58 / 58
Structured Types Functions as Objects
Programming Fundamentals 1
Lesson 5
Pierre Kelsen
2017
1 / 44
Structured Types Functions as Objects
Outline
Structured Types
Functions as Objects
2 / 44
Structured Types Functions as Objects
Structured Types
Structured vs Non-Structured Types
3 / 44
Structured Types Functions as Objects
Structured Types
Structured vs Non-Structured Types
3 / 44
Structured Types Functions as Objects
Structured Types
Sequences
4 / 44
Structured Types Functions as Objects
Structured Types
Tuples
5 / 44
Structured Types Functions as Objects
Structured Types
Operations on Tuples
6 / 44
Structured Types Functions as Objects
Structured Types
Operations on Tuples
6 / 44
Structured Types Functions as Objects
Structured Types
Operations on Tuples
Question
How do you express a tuple with one element?
6 / 44
Structured Types Functions as Objects
Structured Types
Operations on Tuples
Question
How do you express a tuple with one element?
Like this: (1) ? → DEMO.
6 / 44
Structured Types Functions as Objects
Structured Types
Operations on Tuples
Question
How do you express a tuple with one element?
Like this: (1) ? → DEMO.
Answer
No, single element tuples need to be terminated by a comma.
E.g., (1,) denotes a tuple with a single integer 1
6 / 44
Structured Types Functions as Objects
Structured Types
Tuples vs Lists
Question
Tuples and lists look very similar. So what’s the difference?
1
Recall that strings are immutable as well
7 / 44
Structured Types Functions as Objects
Structured Types
Tuples vs Lists
Question
Tuples and lists look very similar. So what’s the difference?
Answer
Tuples are immutable1 while lists are mutable
Definition (Mutability)
A type is mutable if objects of this type can be modified, otherwise
it is immutable.
1
Recall that strings are immutable as well
7 / 44
Structured Types Functions as Objects
Structured Types
Mutations
8 / 44
Structured Types Functions as Objects
Structured Types
Mutations
8 / 44
Structured Types Functions as Objects
Structured Types
Another example
9 / 44
Structured Types Functions as Objects
Structured Types
Another example
9 / 44
Structured Types Functions as Objects
Structured Types
Another example
9 / 44
Structured Types Functions as Objects
Structured Types
Another example (2)
I Let us check object identities by modifying the previous code
snippet:
a = (1,4)
print(id(a))
a += (3,) # shorthand for: a = a + (3,)
print(id(a))
I DEMO
10 / 44
Structured Types Functions as Objects
Structured Types
Another example (2)
I Let us check object identities by modifying the previous code
snippet:
a = (1,4)
print(id(a))
a += (3,) # shorthand for: a = a + (3,)
print(id(a))
I DEMO
I We note that the object identity of the object to which a is
bound changes
I This is because concatenating two sequences creates a new
sequence
I So there is no contradiction to immutability of tuples.
10 / 44
Structured Types Functions as Objects
Structured Types
Mutating Lists
11 / 44
Structured Types Functions as Objects
Structured Types
Mutating Lists
I Since lists are mutable, there should be another way that does
not require creating a second list
11 / 44
Structured Types Functions as Objects
Structured Types
Mutating Lists
2
remember that methods are functions defined inside classes - see lesson 3
12 / 44
Structured Types Functions as Objects
Structured Types
The append Method
13 / 44
Structured Types Functions as Objects
Structured Types
The insert Method
14 / 44
Structured Types Functions as Objects
Structured Types
The insert Method
14 / 44
Structured Types Functions as Objects
Structured Types
Information on the insert Method
15 / 44
Structured Types Functions as Objects
Structured Types
Information on the insert Method
will return:
Help on method\_descriptor:
insert(...)\\
L.insert(index, object) -- insert object before index
15 / 44
Structured Types Functions as Objects
Structured Types
Meaning of insertion
16 / 44
Structured Types Functions as Objects
Structured Types
The remove Method
17 / 44
Structured Types Functions as Objects
Structured Types
The remove Method
17 / 44
Structured Types Functions as Objects
Structured Types
The remove Method
17 / 44
Structured Types Functions as Objects
Structured Types
The remove Method
17 / 44
Structured Types Functions as Objects
Structured Types
Equality vs Identity
I Two objects that have the same identity necessarily have the
same value
I It is possible to redefine the meaning of ”==” for a custom
type.
I If ”==” has not been redefined, ”==” just means object
identity
I for numeric types, ”==” behaves as expected (with ”value”
meaning mathematical value)
Example
For type ”str” equality has been redefined to mean: s1 == s2 iff
they consist of exactly the same characters in the same order.
18 / 44
Structured Types Functions as Objects
Structured Types
Query Methods for List
Question
Why couldn’t we just use the index-method of list to solve the
number search problem?
19 / 44
Structured Types Functions as Objects
Structured Types
Query Methods for List
Question
Why couldn’t we just use the index-method of list to solve the
number search problem?
Answer
Because this method throws an exception when the element is not
in the list → this requires exception handling.
DEMO
19 / 44
Structured Types Functions as Objects
Structured Types
List Comprehension
20 / 44
Structured Types Functions as Objects
Structured Types
List Comprehension
Example
I Suppose you have a list of temperatures in degree Celsius
I You would like to convert the list into temperatures in
Fahrenheit
I The following slide shows a way to do this.
20 / 44
Structured Types Functions as Objects
Structured Types
Converting Temperatures - Version 1
21 / 44
Structured Types Functions as Objects
Structured Types
List Comprehension
22 / 44
Structured Types Functions as Objects
Structured Types
List Comprehension Explained
I The effect of
farenheitTemps = [(t*9/5) + 32 for t in celsiusTemps]
is to create a new list by executing the indicated expression
((t*9/5) + 32) for each element in sequence celsiusTemps
I We can add a condition for elements on which the expression
will be evaluated, e.g.,
L1 = [3, 4, 7, 2]
L2 = [x**2 for x in L1 if x%2==1]
print(L2)
23 / 44
Structured Types Functions as Objects
Structured Types
List Comprehension Explained
I The effect of
farenheitTemps = [(t*9/5) + 32 for t in celsiusTemps]
is to create a new list by executing the indicated expression
((t*9/5) + 32) for each element in sequence celsiusTemps
I We can add a condition for elements on which the expression
will be evaluated, e.g.,
L1 = [3, 4, 7, 2]
L2 = [x**2 for x in L1 if x%2==1]
print(L2) # output: [9, 49]
will place in list L2 the squares of the odd numbers in L1
23 / 44
Structured Types Functions as Objects
Structured Types
The Set Data Type
24 / 44
Structured Types Functions as Objects
Structured Types
The Set Data Type
Example
S = {0, 3, 6, 9}
defines the set of multiples of 3 in the range 0.. 10
Caveat: unlike sets in maths, sets in Python are mutable
24 / 44
Structured Types Functions as Objects
Structured Types
Operations on Sets
Question
Which operations modify the set S?
25 / 44
Structured Types Functions as Objects
Structured Types
Operations on Sets
Question
Which operations modify the set S?
Answer
Only add and remove modify the set S.
25 / 44
Structured Types Functions as Objects
Structured Types
The Empty Set
26 / 44
Structured Types Functions as Objects
Structured Types
The Empty Set
26 / 44
Structured Types Functions as Objects
Structured Types
The Empty Set
26 / 44
Structured Types Functions as Objects
Structured Types
Set Comprehension
27 / 44
Structured Types Functions as Objects
Structured Types
Set Comprehension
27 / 44
Structured Types Functions as Objects
Structured Types
Dictionaries
28 / 44
Structured Types Functions as Objects
Structured Types
Dictionaries
Example
Suppose we have a collection of daily temperatures which we want
to look up by the day (as a string).
I Any other examples?
28 / 44
Structured Types Functions as Objects
Structured Types
Dictionaries
Example
Suppose we have a collection of daily temperatures which we want
to look up by the day (as a string).
I Any other examples?
I In Python we can represent such collections using a dictionary
28 / 44
Structured Types Functions as Objects
Structured Types
Dictionary Example
29 / 44
Structured Types Functions as Objects
Structured Types
Dictionaries vs Sequences
Question
Using the key-value terminology, how would you express the
difference between a sequence and a dictionary?
30 / 44
Structured Types Functions as Objects
Structured Types
Dictionaries vs Sequences
Question
Using the key-value terminology, how would you express the
difference between a sequence and a dictionary?
Answer
A sequence is similar to a dictionary where the keys are consecutive
integers
30 / 44
Structured Types Functions as Objects
Structured Types
Key Types
Example
The following is a valid definition of a dictionary. What are the key
types?
monthNumbers = {'jan': 1, 'feb': 2, 'mar': 3, 5: 'may'}
print(monthNumbers['feb'],' ', monthNumbers[5])
31 / 44
Structured Types Functions as Objects
Structured Types
Key Types
Example
The following is a valid definition of a dictionary. What are the key
types?
monthNumbers = {'jan': 1, 'feb': 2, 'mar': 3, 5: 'may'}
print(monthNumbers['feb'],' ', monthNumbers[5])
# output: 2 may
31 / 44
Structured Types Functions as Objects
Structured Types
Operations on Dictionaries
32 / 44
Structured Types Functions as Objects
Structured Types
Operations on Dictionaries
32 / 44
Structured Types Functions as Objects
Structured Types
Operations on Dictionaries
32 / 44
Structured Types Functions as Objects
Structured Types
Operations on Dictionaries
32 / 44
Structured Types Functions as Objects
Structured Types
Operations on Dictionaries
32 / 44
Structured Types Functions as Objects
Structured Types
Dictionaries as Lists?
33 / 44
Structured Types Functions as Objects
Structured Types
Dictionaries as Lists?
33 / 44
Structured Types Functions as Objects
Structured Types
Dictionaries as Lists?
34 / 44
Structured Types Functions as Objects
Structured Types
Dictionaries as Lists?
34 / 44
Structured Types Functions as Objects
Structured Types
Dictionaries as Lists?
34 / 44
Structured Types Functions as Objects
Structured Types
Dictionaries as Lists?
34 / 44
Structured Types Functions as Objects
Functions as Objects
Example
35 / 44
Structured Types Functions as Objects
Functions as Objects
Example
35 / 44
Structured Types Functions as Objects
Functions as Objects
Example
35 / 44
Structured Types Functions as Objects
Functions as Objects
Functions are Objects
36 / 44
Structured Types Functions as Objects
Functions as Objects
Functions as Arguments
37 / 44
Structured Types Functions as Objects
Functions as Objects
Functions as Arguments
37 / 44
Structured Types Functions as Objects
Functions as Objects
Example
def f(x):
return x*x
def g(x,h): # apply function h to parameter x
return h(x)
print(g(3,f))
38 / 44
Structured Types Functions as Objects
Functions as Objects
Example
def f(x):
return x*x
def g(x,h): # apply function h to parameter x
return h(x)
print(g(3,f)) # output: 9
38 / 44
Structured Types Functions as Objects
Functions as Objects
Another Example
39 / 44
Structured Types Functions as Objects
Functions as Objects
Another Example
I We adapt an earlier example of a function that computes the
sum of squares
I We assume now that the function returns the sum of squares
of the numbers in a list passed as parameter (rather than
limiting ourselves to the numbers 1...n)
I Can we shorten the code by using the applyEach function?
How?
def sumOfSquares(L):
""" Assumes L is a list of numbers
Returns the sum of squares of numbers in L """
s = 0
for x in L :
s += x * x
return s
40 / 44
Structured Types Functions as Objects
Functions as Objects
Another Example
I We adapt an earlier example of a function that computes the
sum of squares
I We assume now that the function returns the sum of squares
of the numbers in a list passed as parameter (rather than
limiting ourselves to the numbers 1...n)
I Can we shorten the code by using the applyEach function?
How?
def sumOfSquares(L):
""" Assumes L is a list of numbers
Returns the sum of squares of numbers in L """
s = 0
for x in L :
s += x * x
return s
I Hint: use the built-in function sum.
40 / 44
Structured Types Functions as Objects
Functions as Objects
Another Example
def sumOfSquares(L):
""" Assumes L is a list of numbers
Returns the sum of squares of numbers in L """
return sum(applyForEach(L, f))
# assuming f(x) returns x*x
41 / 44
Structured Types Functions as Objects
Functions as Objects
Another Example
def sumOfSquares(L):
""" Assumes L is a list of numbers
Returns the sum of squares of numbers in L """
return sum(applyForEach(L, f))
# assuming f(x) returns x*x
41 / 44
Structured Types Functions as Objects
Functions as Objects
Expressing Simple Functions
42 / 44
Structured Types Functions as Objects
Functions as Objects
Lambda Expressions
Example
The lambda expression lambda x: x*x defines a function that
computes the square of a number
43 / 44
Structured Types Functions as Objects
Functions as Objects
Applying Lambda Expressions
def sumOfSquares(L):
""" Assumes L is a list of numbers
Returns the sum of squares of numbers in L """
return sum(applyForEach(L, lambda x: x*x))
44 / 44
Files Exceptions and Assertions
Programming Fundamentals 1
Lesson 6
Pierre Kelsen
2017
1 / 52
Files Exceptions and Assertions
Outline
Files
2 / 52
Files Exceptions and Assertions
Files
Text
3 / 52
Files Exceptions and Assertions
Files
Transient versus Persistent Data
I The string read by the input function on the last example only
exists during the lifetime of the program
I This string is thus an example of transient data
I If data exists outside the lifetime of the program, we call it
persistent
I Note that you have not seen yet persistent data in your
practicals
Question
Can you think of scenarios in which you would need to process
persistent data?
4 / 52
Files Exceptions and Assertions
Files
Text Files
5 / 52
Files Exceptions and Assertions
Files
Opening Text Files
I Before you can read text from a text file you must open the
text file
I Can you think of analogy in the real world?
6 / 52
Files Exceptions and Assertions
Files
Opening Text Files
I Before you can read text from a text file you must open the
text file
I Can you think of analogy in the real world?
I In order to read a book, you must first open it
I Text files can be opened using the built-in function open
6 / 52
Files Exceptions and Assertions
Files
Opening Text Files
I Before you can read text from a text file you must open the
text file
I Can you think of analogy in the real world?
I In order to read a book, you must first open it
I Text files can be opened using the built-in function open
Question
How can we look up information on open?
6 / 52
Files Exceptions and Assertions
Files
Opening Text Files
I Before you can read text from a text file you must open the
text file
I Can you think of analogy in the real world?
I In order to read a book, you must first open it
I Text files can be opened using the built-in function open
Question
How can we look up information on open?
Answer
By typing help(open) in the shell → DEMO
6 / 52
Files Exceptions and Assertions
Files
Simplest Form of open
7 / 52
Files Exceptions and Assertions
Files
Simplest Form of open
7 / 52
Files Exceptions and Assertions
Files
Current Directory
8 / 52
Files Exceptions and Assertions
Files
Current Directory
8 / 52
Files Exceptions and Assertions
Files
An Example
9 / 52
Files Exceptions and Assertions
Files
An Example
9 / 52
Files Exceptions and Assertions
Files
Reading the File
10 / 52
Files Exceptions and Assertions
Files
Example Program: First Attempt
11 / 52
Files Exceptions and Assertions
Files
Example Program: First Attempt
11 / 52
Files Exceptions and Assertions
Files
Review: Assignment Statement
12 / 52
Files Exceptions and Assertions
Files
Example Program: Second Attempt
13 / 52
Files Exceptions and Assertions
Files
Example Program: Second Attempt
13 / 52
Files Exceptions and Assertions
Files
Example program: Version 2
14 / 52
Files Exceptions and Assertions
Files
Example program: Version 2
14 / 52
Files Exceptions and Assertions
Files
Example program: Version 2
14 / 52
Files Exceptions and Assertions
Files
Example program: Version 3
15 / 52
Files Exceptions and Assertions
Files
The print Function
16 / 52
Files Exceptions and Assertions
Files
The print Function
16 / 52
Files Exceptions and Assertions
Files
Example program: Version 4
17 / 52
Files Exceptions and Assertions
Files
File Access Modes
18 / 52
Files Exceptions and Assertions
Files
Writing Text Files
19 / 52
Files Exceptions and Assertions
Files
About Buffers
20 / 52
Files Exceptions and Assertions
Files
About Buffers
20 / 52
Files Exceptions and Assertions
Files
Path Names
I All examples above assume the file is located in the current
directory
I If this is not the case, we can give the absolute path name of
the file
I The form of absolute path names depends on the platform,
e.g.,
I "C:\MyFiles\file1.txt" could be an absolute path name
(including the file name) on Windows
I "/Users/pierre/MyFiles/file1.txt" could be an absolute
path name (including the file name) on a Mac
I Python allows to use the same separator - ”/” - on all
platforms
I we can thus rewrite the Windows path above as:
"C:/MyFiles/file1.txt"
21 / 52
Files Exceptions and Assertions
Files
Relative Path Names
22 / 52
Files Exceptions and Assertions
23 / 52
Files Exceptions and Assertions
Question
Why do we need to deal with exceptions?
23 / 52
Files Exceptions and Assertions
Question
Why do we need to deal with exceptions?
Answer
Because we make mistakes in our coding.
Example:
t = [1,2,3]
print(t[3])
I DEMO 23 / 52
Files Exceptions and Assertions
Question
Why do we need to deal with exceptions?
Answer
Because we make mistakes in our coding.
Example:
t = [1,2,3]
print(t[3])
I DEMO → raises an exception of type IndexError 23 / 52
Files Exceptions and Assertions
24 / 52
Files Exceptions and Assertions
24 / 52
Files Exceptions and Assertions
24 / 52
Files Exceptions and Assertions
25 / 52
Files Exceptions and Assertions
26 / 52
Files Exceptions and Assertions
import math
print(math.factorial(4))
print(math.factorial(-1))
I DEMO
26 / 52
Files Exceptions and Assertions
import math
print(math.factorial(4))
print(math.factorial(-1))
I DEMO
I The second print statement raises a ValueError since the
factorial function expects a non-negative argument
26 / 52
Files Exceptions and Assertions
27 / 52
Files Exceptions and Assertions
27 / 52
Files Exceptions and Assertions
successFailureRatio = numSuccesses/float(numFailures)
print('The success/failure ratio is', successFailureRatio)
print('Now here')
28 / 52
Files Exceptions and Assertions
successFailureRatio = numSuccesses/float(numFailures)
print('The success/failure ratio is', successFailureRatio)
print('Now here')
28 / 52
Files Exceptions and Assertions
try:
statement(s)
except [expression]:
statement(s)
29 / 52
Files Exceptions and Assertions
1 try:
2 successFailureRatio = numSuccesses/float(numFailures)
3 print('The success/failure ratio is', successFailureRatio)
4 except ZeroDivisionError:
5 print('No failures')
6 print('Now here')
30 / 52
Files Exceptions and Assertions
31 / 52
Files Exceptions and Assertions
31 / 52
Files Exceptions and Assertions
31 / 52
Files Exceptions and Assertions
try:
val = int(input('Enter an integer: '))
print('The square of the number you entered is:', val**2)
except ValueError:
print('The entered number is not an integer')
32 / 52
Files Exceptions and Assertions
I The following code repeatedly ask the user for a number until
a valid number is given:
while True:
val = input('Enter a number: ')
try:
val = int(val)
print('The square of the number you entered is:',val**2)
break # exit the while loop
except ValueError:
print('The entered number is not an integer')
I This code guarantees that the code following the while loop
can only be reached once val has a proper integer value
33 / 52
Files Exceptions and Assertions
I The code is more general than the code on the previous slide.
Why?
34 / 52
Files Exceptions and Assertions
I The code is more general than the code on the previous slide.
Why?Because it works for any type.
I We can ask for an integer like this:
requestInput(int, 'Please enter an integer: ')
34 / 52
Files Exceptions and Assertions
35 / 52
Files Exceptions and Assertions
35 / 52
Files Exceptions and Assertions
try:
s = input('Enter a sequence of numbers: ')
numberSequence = s.split()
print(numberSequence)
inverseSequence = [1/int(x) for x in numberSequence]
print(inverseSequence)
except ValueError:
print('invalid number')
except ZeroDivisionError:
print('Attempted to divide by 0')
try:
s = input('Enter a sequence of numbers: ')
numberSequence = s.split()
print(numberSequence)
inverseSequence = [1/int(x) for x in numberSequence]
print(inverseSequence)
except (ValueError, ZeroDivisonError):
print('ValueError or ZeroDivisionError occurred')
37 / 52
Files Exceptions and Assertions
try:
s = input('Enter a sequence of numbers: ')
numberSequence = s.split()
print(numberSequence)
inverseSequence = [1/int(x) for x in numberSequence]
print(inverseSequence)
except:
print('Some error occurred')
38 / 52
Files Exceptions and Assertions
try:
f = open('test.txt')
s = f.readline()
except IOError as e:
print('IO error', e)
40 / 52
Files Exceptions and Assertions
def f():
g()
def g():
h()
def h():
i = int(input('Enter a number please: '))
print(i*i)
41 / 52
Files Exceptions and Assertions
42 / 52
Files Exceptions and Assertions
43 / 52
Files Exceptions and Assertions
44 / 52
Files Exceptions and Assertions
46 / 52
Files Exceptions and Assertions
index(...)
L.index(value, [start, [stop]]) ->
integer -- return first index of value.
Raises ValueError if the value is not present.
46 / 52
Files Exceptions and Assertions
47 / 52
Files Exceptions and Assertions
48 / 52
Files Exceptions and Assertions
49 / 52
Files Exceptions and Assertions
49 / 52
Files Exceptions and Assertions
50 / 52
Files Exceptions and Assertions
51 / 52
Files Exceptions and Assertions
PROCEDURE DIVISION.
DisplayPrompt.
DISPLAY "I did it".
STOP RUN.
52 / 52
Testing
Programming Fundamentals 1
Lesson 7
Pierre Kelsen
2017
1 / 44
Testing
Outline
Testing
2 / 44
Testing
Testing
Testing vs Debugging
3 / 44
Testing
Testing
Testing vs Debugging: The Big Picture
4 / 44
Testing
Testing
Aim of Testing
Observation
Program testing can be used to show the presence of bugs, but
never to show their absence.
Edsgar W. Dijkstra
5 / 44
Testing
Testing
Aim of Testing (2)
I A similar quote attributed to Albert Einstein (and paraphrased
here):
No amount of experimentation can ever prove me right; a
single experiment can prove me wrong.
Albert Einstein
6 / 44
Testing
Testing
Limits of Testing
Question
Why can’t we just test all possible inputs?
7 / 44
Testing
Testing
Limits of Testing
Question
Why can’t we just test all possible inputs?
Answer
Because there are too many. E.g., suppose you wrote a function
that tests whether a number is prime. How many possible inputs
are there?
7 / 44
Testing
Testing
Limits of Testing
Question
Why can’t we just test all possible inputs?
Answer
Because there are too many. E.g., suppose you wrote a function
that tests whether a number is prime. How many possible inputs
are there?
In Python 3, there is no limit to the size of an integer!
7 / 44
Testing
Testing
Test Suite
8 / 44
Testing
Testing
Test Suite
8 / 44
Testing
Testing
Partition
1
https://en.wikipedia.org/wiki/Partition of a set
9 / 44
Testing
Testing
Partition
Definition1
In mathematics, a partition of a set is a grouping of the set’s
elements into non-empty subsets, in such a way that every element
is included in one and only one of the subsets.
Question
Can you give examples of set partitions?
1
https://en.wikipedia.org/wiki/Partition of a set
9 / 44
Testing
Testing
From Partitions to Test Suites
10 / 44
Testing
Testing
From Partitions to Test Suites
10 / 44
Testing
Testing
Finding Test Suites
11 / 44
Testing
Testing
Black-Box Testing
12 / 44
Testing
Testing
Black-Box Testing
12 / 44
Testing
Testing
Black-Box Testing
12 / 44
Testing
Testing
Black-Box Testing
12 / 44
Testing
Testing
Testers vs Implementers
Question
Why can it be advantageous for testers to be distinct from
implementers?
13 / 44
Testing
Testing
Testers vs Implementers
Question
Why can it be advantageous for testers to be distinct from
implementers?
Answer
Test suites may exhibit mistakes that are correlated with mistakes
in the code. How?
13 / 44
Testing
Testing
Testers vs Implementers
Question
Why can it be advantageous for testers to be distinct from
implementers?
Answer
Test suites may exhibit mistakes that are correlated with mistakes
in the code. How?
Example
Suppose that the programmer made the incorrect assumption that
a function is never called with a negative number.
If the programmer writes the test suite, (s)he is likely to repeat the
same mistake (by not including cases where the argument is
negative).
13 / 44
Testing
Testing
Specifications
I Since black-box tests are not based on the code, they must be
based on the requirements of the code
Question
We have already seen a method for definining the requirements of
a function in Python. What is it?
14 / 44
Testing
Testing
Specifications
I Since black-box tests are not based on the code, they must be
based on the requirements of the code
Question
We have already seen a method for definining the requirements of
a function in Python. What is it?
Answer
The requirements can be specified by a special comment in a
function called a docstring. The docstring defines the assumptions
on the input and the guarantees on the output. We called this a
specification or a contract for the function.
14 / 44
Testing
Testing
Example Specification
Example
def ageInterval(x):
"""Assumes x is a non-negative integer in the range 0..99
Returns 0 if 0<=x<=15, 1 if 16<=x<18,
2 if 18<=x<=60, 3 if 60<x<=99
"""
15 / 44
Testing
Testing
Boundary-Values Technique
Question
How would you define the boundary values of the ageInterval
function?
16 / 44
Testing
Testing
Boundary-Values Technique
Question
How would you define the boundary values of the ageInterval
function?
Answer
Define the boundary values as those values that are the endpoints
of the age intervals being tested.
In this case: 0, 15, 16, 18 60, 99
16 / 44
Testing
Testing
Boundary-Values Technique: Application
Question
Do you notice anything special about the test suite?
17 / 44
Testing
Testing
Boundary-Values Technique: Application
Question
Do you notice anything special about the test suite?
Answer
The first and last values are not valid inputs according to the
requirements.
17 / 44
Testing
Testing
Invalid inputs
18 / 44
Testing
Testing
Invalid inputs
18 / 44
Testing
Testing
Invalid inputs
18 / 44
Testing
Testing
Invalid inputs
18 / 44
Testing
Testing
Defensive Testing
19 / 44
Testing
Testing
Defensive Testing
19 / 44
Testing
Testing
Equivalence Class Testing
20 / 44
Testing
Testing
Equivalence Class Testing: Application
21 / 44
Testing
Testing
Glass-Box Testing
22 / 44
Testing
Testing
Glass-Box Testing: Example
def isPrime(x):
"""Assumes x is a non-negative integer
Returns True if x is prime, False otherwise"""
if x<=2:
return False
for i in range(2,x):
if x%i == 0:
return False
return True
23 / 44
Testing
Testing
Glass-Box Testing: Example
24 / 44
Testing
Testing
Glass-Box Testing: Example
24 / 44
Testing
Testing
Glass-Box Testing: Example
24 / 44
Testing
Testing
Paths through Code
I Different input values give rise to different statements being
executed
I Each sequence of statements that can be executed from start
to finish is called a path
I Example of paths (as sequences of line numbers) are given
below
1 def isPrime(x):
2 if x<=2:
3 return False Path for x=1:
4 for i in range(2,x):
5 if x%i == 0:
6 return False
7 return True
25 / 44
Testing
Testing
Paths through Code
I Different input values give rise to different statements being
executed
I Each sequence of statements that can be executed from start
to finish is called a path
I Example of paths (as sequences of line numbers) are given
below
1 def isPrime(x):
2 if x<=2:
3 return False Path for x=1: 2, 3
4 for i in range(2,x):
5 if x%i == 0:
6 return False
7 return True
25 / 44
Testing
Testing
Paths through Code
I Different input values give rise to different statements being
executed
I Each sequence of statements that can be executed from start
to finish is called a path
I Example of paths (as sequences of line numbers) are given
below
1 def isPrime(x):
2 if x<=2:
3 return False Path for x=1: 2, 3
4 for i in range(2,x): Path for x=3:
5 if x%i == 0:
6 return False
7 return True
25 / 44
Testing
Testing
Paths through Code
I Different input values give rise to different statements being
executed
I Each sequence of statements that can be executed from start
to finish is called a path
I Example of paths (as sequences of line numbers) are given
below
1 def isPrime(x):
2 if x<=2:
3 return False Path for x=1: 2, 3
4 for i in range(2,x): Path for x=3: 2, 4, 5, 7
5 if x%i == 0:
6 return False
7 return True
25 / 44
Testing
Testing
Paths through Code
I Different input values give rise to different statements being
executed
I Each sequence of statements that can be executed from start
to finish is called a path
I Example of paths (as sequences of line numbers) are given
below
1 def isPrime(x):
2 if x<=2:
3 return False Path for x=1: 2, 3
4 for i in range(2,x): Path for x=3: 2, 4, 5, 7
5 if x%i == 0: Path for x=4:
6 return False
7 return True
25 / 44
Testing
Testing
Paths through Code
I Different input values give rise to different statements being
executed
I Each sequence of statements that can be executed from start
to finish is called a path
I Example of paths (as sequences of line numbers) are given
below
1 def isPrime(x):
2 if x<=2:
3 return False Path for x=1: 2, 3
4 for i in range(2,x): Path for x=3: 2, 4, 5, 7
5 if x%i == 0: Path for x=4: 2, 4, 5, 6
6 return False
7 return True
25 / 44
Testing
Testing
Path-Completeness
26 / 44
Testing
Testing
Path-Completeness and Correctness
I Suppose we do have a path-complete test suite
I Is that sufficient to detect all errors?
27 / 44
Testing
Testing
Path-Completeness and Correctness
I Suppose we do have a path-complete test suite
I Is that sufficient to detect all errors?
I No, it is not - see example below:
def abs(x):
"""Assumes x is an int
Returns absolute value of x"""
if x < -1:
return -x
else:
return x
27 / 44
Testing
Testing
Path-Completeness and Correctness
I Suppose we do have a path-complete test suite
I Is that sufficient to detect all errors?
I No, it is not - see example below:
def abs(x):
"""Assumes x is an int
Returns absolute value of x"""
if x < -1:
return -x
else:
return x
Testing
Guidelines
28 / 44
Testing
Testing
If-Statements and Except Clauses
29 / 44
Testing
Testing
For-Loops and While-Loops
30 / 44
Testing
Testing
Recursive Functions
I For testing recursive functions include test cases that lead to:
I no recursive call
I exactly one recursive call
I more than one recursive call
31 / 44
Testing
Testing
Unit Testing vs Integration Testing
32 / 44
Testing
Testing
Unit Testing
33 / 44
Testing
Testing
Example
34 / 44
Testing
Testing
Example
35 / 44
Testing
Testing
Example
I Let us save the text on the previous slide into a text file
”testPrime.txt”
I DEMO
36 / 44
Testing
Testing
Example
I Let us save the text on the previous slide into a text file
”testPrime.txt”
I DEMO
I We can now use doctest to read this file as follows (in the
shell):
>>> import doctest
>>> doctest.testfile("testPrime.txt")
I Run this Python code → DEMO
36 / 44
Testing
Testing
Result
37 / 44
Testing
Testing
Explaining the Result
38 / 44
Testing
Testing
Explaining the Result (2)
39 / 44
Testing
Testing
The testfile Function
40 / 44
Testing
Testing
Regressions
41 / 44
Testing
Testing
Regressions
41 / 44
Testing
Testing
Regressions
41 / 44
Testing
Testing
Regression Testing
42 / 44
Testing
Testing
Regression Testing
42 / 44
Testing
Testing
Integration Testing
43 / 44
Testing
Testing
Integration Testing
Example
Compare the problem of specifying the behavior of a word
processor to that of a function that counts the number of
occurrences of a word in a document.
43 / 44
Testing
Testing
Software Quality Assurance
44 / 44
Debugging
Programming Fundamentals 1
Lesson 8
Pierre Kelsen
2017
1 / 43
Debugging
Outline
Debugging
2 / 43
Debugging
Debugging
Software Bugs
Definition1
A software bug is an error, flaw, failure or fault in a computer
program or system that causes it to produce an incorrect or
unexpected result, or to behave in unintended ways.
1
https://en.wikipedia.org/wiki/Software bug
3 / 43
Debugging
Debugging
Origin of Bugs
4 / 43
Debugging
Debugging
Origin of Software Bugs
5 / 43
Debugging
Debugging
Types of Software Bugs: Overt vs Covert
6 / 43
Debugging
Debugging
Types of Software Bugs: Overt vs Covert
6 / 43
Debugging
Debugging
Types of Software Bugs: Persistent vs Intermittent
7 / 43
Debugging
Debugging
Software Bugs: The Good, the Bad and the Ugly
I The best bugs to have are those that are overt and persistent
since they are easiest to discover
I Next are those that are overt but intermittent; these are
harder to detect and are more likely to occur in production
software
I Worst are those that are covert
I possibly only discovered after many ”wrong” answers have
been produced
I Can you think about a possible scenario with bad
consequences?
8 / 43
Debugging
Debugging
Software Bugs: The Good, the Bad and the Ugly
I The best bugs to have are those that are overt and persistent
since they are easiest to discover
I Next are those that are overt but intermittent; these are
harder to detect and are more likely to occur in production
software
I Worst are those that are covert
I possibly only discovered after many ”wrong” answers have
been produced
I Can you think about a possible scenario with bad
consequences?
I E.g., software that evaluates the credit worthiness of a bank
customer
8 / 43
Debugging
Debugging
What is Debugging?
9 / 43
Debugging
Debugging
What is Debugging?
9 / 43
Debugging
Debugging
About Debugging
10 / 43
Debugging
Debugging
Programming and Role Playing
Question
What does programming have in common with a role-playing
game?
11 / 43
Debugging
Debugging
Programming and Role Playing
12 / 43
Debugging
Debugging
Programming and Role Playing
12 / 43
Debugging
Debugging
Programming and Role Playing
12 / 43
Debugging
Debugging
Programming and Role Playing
12 / 43
Debugging
Debugging
Programming and Role Playing
12 / 43
Debugging
Debugging
Programming and Role Playing
12 / 43
Debugging
Debugging
10 Truths about Debugging
2
http://cs.stanford.edu/people/nick/compdocs/Debugging.pdf
13 / 43
Debugging
Debugging
Truth 1: Intuition vs Facts
Truth 1
Intuition and hunches are great - you just have to test them out.
When a hunch and a fact collide, the fact wins.
14 / 43
Debugging
Debugging
Truth 2: Simplicity vs Complexity
Truth 2
Dont look for complex explanations. Even the simplest omission or
typo can lead to very weird behavior. Dont just sweep your eye
over that series of simple statements assuming that they are too
simple to be wrong.
15 / 43
Debugging
Debugging
Truth 3: Importance of Watching
Truth 3
The clue to what is wrong in your code is in the values of your
variables and the flow of control. Try to see what the facts are
pointing to. The computer is not trying to mislead you. Work
from the facts.
16 / 43
Debugging
Debugging
Truth 4: Test as You Go
Truth 4
If your code was working a minute ago, but now it doesnt–what
was the last thing you changed? This incredibly reliable rule of
thumb is the reason your section leader told you to test your code
as you go rather than all at once.
17 / 43
Debugging
Debugging
Truth 5: Be Prudent
Truth 5
Do not change your code haphazardly trying to track down a bug.
This is sort of like a scientist who changes more than one variable
in an experiment at a time. It makes the observed behavior much
more difficult to interpret, and you tend to introduce new bugs.
18 / 43
Debugging
Debugging
Truth 6: Related Bugs
Truth 6
If you find some wrong code that does not seem to be related to
the bug you were tracking, fix the wrong code anyway. Many times
the wrong code was related to or obscured the bug in a way you
had not imagined.
19 / 43
Debugging
Debugging
Truth 7: Explain your Reasoning
Truth 7
You should be able to explain in Sherlock Holmes style the series
of facts, tests, and deductions that led you to find a bug.
Alternately, if you have a bug but cant pinpoint it, then you should
be able to give an argument to a critical third party detailing why
each one of your functions cannot contain the bug. One of these
arguments will contain a flaw since one of your functions does in
fact contain a bug. Trying to construct the arguments may help
you to see the flaw.
20 / 43
Debugging
Debugging
Truth 8: Question Yourself
Truth 8
Be critical of your beliefs about your code. Its almost impossible to
see a bug in a function when your instinct is that the function is
innocent. Only when the facts have proven without question that
the function is not the source of the problem should you assume it
to be correct.
21 / 43
Debugging
Debugging
Truth 9: Guess Anyway
Truth 9
Although you need to be systematic, there is still an enormous
amount of room for beliefs, hunches, guesses, etc. Use your
intuition about where the bug probably is to direct the order that
you check things in your systematic search. Check the functions
you suspect the most first. Good instincts will come with
experience.
22 / 43
Debugging
Debugging
Truth 10: Take a Break
Truth 10
Debugging code is more mentally demanding than writing code.
The longer you try to track down a bug without success, the less
perspective you tend to have. Realize when you have lost the
perspective on your code to debug. Take a break. Get some sleep.
You cannot debug when you are not seeing things clearly. Many
times a programmer can spend hours late at night hunting for a
bug only to finally give up at 4:00A.M. The next day, they find the
bug in 10 minutes.
23 / 43
Debugging
Debugging
Getting Down to Business
24 / 43
Debugging
Debugging
A Buggy Program
def isPal(x):
"""Assumes x is a list
Returns True if the list is a palindrome; False otherwise"""
temp = x
temp.reverse
if temp == x:
return True
else:
return False
# main program
n = int(input('Enter number n:'))
for i in range(n):
result = []
elem = input('Enter element: ')
result.append(elem)
if isPal(result):
print('Yes')
else:
print('No') 25 / 43
Debugging
Debugging
Testing the Buggy Program
26 / 43
Debugging
Debugging
Testing the Buggy Program
26 / 43
Debugging
Debugging
Testing the Buggy Program
26 / 43
Debugging
Debugging
Setting Breakpoints
27 / 43
Debugging
Debugging
Setting Breakpoints
27 / 43
Debugging
Debugging
Setting Breakpoints
28 / 43
Debugging
Debugging
Setting Breakpoints
28 / 43
Debugging
Debugging
Debug Mode
29 / 43
Debugging
Debugging
Where to Break
30 / 43
Debugging
Debugging
Where to Break
Where to look?
30 / 43
Debugging
Debugging
Binary Code Search
31 / 43
Debugging
Debugging
Looking around
I What are we going to do when the program pauses at the
breakpoint?
32 / 43
Debugging
Debugging
Looking around
I What are we going to do when the program pauses at the
breakpoint?
I We inspect the value of variables to check for abnormalities
I Pycharm provides a variable window which shows the value of
relevant variables
I DEMO
I What variable value is most relevant?
32 / 43
Debugging
Debugging
Looking around
I What are we going to do when the program pauses at the
breakpoint?
I We inspect the value of variables to check for abnormalities
I Pycharm provides a variable window which shows the value of
relevant variables
I DEMO
I What variable value is most relevant?
I The result list that will be passed as argument to the isPal
function
32 / 43
Debugging
Debugging
What to do next
33 / 43
Debugging
Debugging
What to do next
33 / 43
Debugging
Debugging
What to do next
33 / 43
Debugging
Debugging
Stepwise execution
34 / 43
Debugging
Debugging
Restarting
Question
So why does result not ”behave” correctly?
35 / 43
Debugging
Debugging
Restarting
Question
So why does result not ”behave” correctly?
Answer
Because result is reinitialized in every iteration. How do we fix this?
35 / 43
Debugging
Debugging
Restarting
Question
So why does result not ”behave” correctly?
Answer
Because result is reinitialized in every iteration. How do we fix this?
By initializing result once before the loop.
35 / 43
Debugging
Debugging
Fixing the Error
# main program
n = int(input('Enter number n:'))
result = [] # initialization has been moved here
for i in range(n):
elem = input('Enter element: ')
result.append(elem)
if isPal(result):
print('Yes')
else:
print('No')
36 / 43
Debugging
Debugging
Fixing the Error
# main program
n = int(input('Enter number n:'))
result = [] # initialization has been moved here
for i in range(n):
elem = input('Enter element: ')
result.append(elem)
if isPal(result):
print('Yes')
else:
print('No')
Debugging
Retesting
37 / 43
Debugging
Debugging
Retesting
37 / 43
Debugging
Debugging
Retesting
37 / 43
Debugging
Debugging
Testing the Function
38 / 43
Debugging
Debugging
Testing the Function
38 / 43
Debugging
Debugging
Testing the Function
38 / 43
Debugging
Debugging
Testing the Function
38 / 43
Debugging
Debugging
One More Fix
39 / 43
Debugging
Debugging
One More Fix
I Are we done?
39 / 43
Debugging
Debugging
One More Fix
I Are we done?
No: the output is still wrong. Why?
39 / 43
Debugging
Debugging
Final Fix
I x and temp are bound to the same list object
I when we reverse the list bound to temp, it has the same effect
on x
I we need to do a copy of the list bound to x, and then reverse
that copy
def isPal(x):
"""Assumes x is a list
Returns True if the list is a palindrome; False otherwise""
temp = x.copy() # performs shallow copy of list x
temp.reverse() # before: temp.reverse
if temp == x:
return True
else:
return False
Debugging
Stack Trace
41 / 43
Debugging
Debugging
Watches
42 / 43
Debugging
Debugging
Conditional Breakpoints
43 / 43
Debugging
Debugging
Conditional Breakpoints
43 / 43
Iterators Generators
Programming Fundamentals 1
Lesson 9
Pierre Kelsen
2017
1 / 46
Iterators Generators
Outline
Iterators
Generators
2 / 46
Iterators Generators
Iterators
For-Loops
3 / 46
Iterators Generators
Iterators
From Expressions to Iterators
4 / 46
Iterators Generators
Iterators
From Expressions to Iterators
4 / 46
Iterators Generators
Iterators
From Expressions to Iterators
4 / 46
Iterators Generators
Iterators
From Expressions to Iterators (2)
5 / 46
Iterators Generators
Iterators
From Expressions to Iterators (3)
ITERATOR
Iterates over
(Using next requests)
EXPRESSION
(must be iterable)
Iterating in Python
6 / 46
Iterators Generators
Iterators
Iterables
7 / 46
Iterators Generators
Iterators
The iter-function
8 / 46
Iterators Generators
Iterators
Iterators
9 / 46
Iterators Generators
Iterators
Example
I So how do we iterate over an iterable expression?
10 / 46
Iterators Generators
Iterators
Example
I So how do we iterate over an iterable expression?
I obtain an iterator from the expression
10 / 46
Iterators Generators
Iterators
Example
I So how do we iterate over an iterable expression?
I obtain an iterator from the expression
I keep invoking the next() function with the iterator as
argument to obtain the next item
10 / 46
Iterators Generators
Iterators
Example
I So how do we iterate over an iterable expression?
I obtain an iterator from the expression
I keep invoking the next() function with the iterator as
argument to obtain the next item
Example
L =[2, 5, 7]
i = iter(L)
while True:
x = next(i)
print('Item: ', x)
I DEMO
10 / 46
Iterators Generators
Iterators
Example
I So how do we iterate over an iterable expression?
I obtain an iterator from the expression
I keep invoking the next() function with the iterator as
argument to obtain the next item
Example
L =[2, 5, 7]
i = iter(L)
while True:
x = next(i)
print('Item: ', x)
I DEMO
I this code raises a StopIteration exception after the last item
has been printed
10 / 46
Iterators Generators
Iterators
Rewriting for-loops
11 / 46
Iterators Generators
Iterators
The range function
for i in range(10):
if i%3==0:
print (i)
12 / 46
Iterators Generators
Iterators
The range function
for i in range(10):
if i%3==0:
print (i)
12 / 46
Iterators Generators
Iterators
What is range?
13 / 46
Iterators Generators
Iterators
What is range?
13 / 46
Iterators Generators
Iterators
range is iterable
14 / 46
Iterators Generators
Iterators
range is iterable
14 / 46
Iterators Generators
Iterators
Iterables vs explicit lists
I So what is the advantage of implementing for-loops using
iterables
15 / 46
Iterators Generators
Iterators
Iterables vs explicit lists
I So what is the advantage of implementing for-loops using
iterables
I do not need to keep all the items in memory at once
I thus much more memory-efficient (and possibly faster)
I The following example illustrates this:
N = 10**12
for i in range(N):
if i >= 10:
break
print(i, end=', ')
I DEMO
15 / 46
Iterators Generators
Iterators
Iterables vs explicit lists
I So what is the advantage of implementing for-loops using
iterables
I do not need to keep all the items in memory at once
I thus much more memory-efficient (and possibly faster)
I The following example illustrates this:
N = 10**12
for i in range(N):
if i >= 10:
break
print(i, end=', ')
I DEMO
I This code executes instantly because only 11 items are
constructed explicitly (numbers 0..10)
15 / 46
Iterators Generators
Iterators
Iterables as lists
16 / 46
Iterators Generators
Iterators
Iterables as lists
16 / 46
Iterators Generators
Iterators
Iterables as lists
16 / 46
Iterators Generators
Iterators
The enumerate function
17 / 46
Iterators Generators
Iterators
The enumerate Function: Example
I Output:
18 / 46
Iterators Generators
Iterators
The enumerate Function: Example
I Output:
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
18 / 46
Iterators Generators
Iterators
The map function
19 / 46
Iterators Generators
Iterators
The map function
19 / 46
Iterators Generators
Iterators
The map function: general case
20 / 46
Iterators Generators
Iterators
Example for the General Case
a = (1, 5, 8)
b = (2, 6, 3)
sum(map(lambda x,y: x*y, a, b))
21 / 46
Iterators Generators
Iterators
The filter Function
Example
filter(lambda x: x%2==1, range(10))
Output:
22 / 46
Iterators Generators
Iterators
The filter Function
Example
filter(lambda x: x%2==1, range(10))
22 / 46
Iterators Generators
Iterators
The itertools Module
23 / 46
Iterators Generators
Iterators
Infinite Iterators
24 / 46
Iterators Generators
Iterators
Infinite Iterators
24 / 46
Iterators Generators
Iterators
The count Iterator
25 / 46
Iterators Generators
Iterators
The count Iterator: Example
26 / 46
Iterators Generators
Iterators
Combinatoric Iterators
Example
>>> from itertools import permutations
>>> a= permutations(range(4))
I DEMO
27 / 46
Iterators Generators
Generators
Definition
28 / 46
Iterators Generators
Generators
Definition(2)
29 / 46
Iterators Generators
Generators
General Form of range
30 / 46
Iterators Generators
Generators
General Form of range: Example
31 / 46
Iterators Generators
Generators
General Form of range: Example
31 / 46
Iterators Generators
Generators
General Form of range: Example
31 / 46
Iterators Generators
Generators
General Form of range: Example
31 / 46
Iterators Generators
Generators
General Form of range: Example
31 / 46
Iterators Generators
Generators
General Form of range: Example
31 / 46
Iterators Generators
Generators
From Generators to Iterators
32 / 46
Iterators Generators
Generators
Calling the Generator
for i in updown(3):
print(i)
I Output:
1
2
3
2
1
33 / 46
Iterators Generators
Generators
Iterators are Iterables!
34 / 46
Iterators Generators
Generators
Iterators are Iterables!
34 / 46
Iterators Generators
Generators
Generators as Functions
I We can simulate a generator by a function that returns a list
of items
I For the previous example we can write a function that returns
the list [1,..., n, n-1,..., 1]
I An example implementation is the following:
def updown2(n):
l1 = list(range(1,n))
l2 = list(range(n, 0, -1))
return l1+l2
The following statements will then produce the same output:
for i in updown2(3):
print(i)
35 / 46
Iterators Generators
Generators
Lazy Evaluation
36 / 46
Iterators Generators
Generators
Lazy Evaluation
36 / 46
Iterators Generators
Generators
Lazy Evaluation
36 / 46
Iterators Generators
Generators
Generator Expressions
37 / 46
Iterators Generators
Generators
Generator Expressions
37 / 46
Iterators Generators
Generators
Infinite Generator
38 / 46
Iterators Generators
Generators
Single Use vs Multiple Use
I Iterators (and therefore also generator objects) have an
internal state
I Once they have produced all items, they terminate and cannot
be used again
I Thus
a = (n for n in range(4))
for i in a:
print(i,end=' ')
for i in a:
print(i,end=' ')
will output:
39 / 46
Iterators Generators
Generators
Single Use vs Multiple Use
I Iterators (and therefore also generator objects) have an
internal state
I Once they have produced all items, they terminate and cannot
be used again
I Thus
a = (n for n in range(4))
for i in a:
print(i,end=' ')
for i in a:
print(i,end=' ')
will output:
0123
I There is only one line of output since a has terminated after
the first loop
39 / 46
Iterators Generators
Generators
Single Use vs Multiple Use (2)
will output:
40 / 46
Iterators Generators
Generators
Single Use vs Multiple Use (2)
will output:
01230123
40 / 46
Iterators Generators
Generators
Single Use vs Multiple Use (2)
will output:
41 / 46
Iterators Generators
Generators
Single Use vs Multiple Use (2)
will output:
0 1 4 9 16 25 36
doing something in between
49 64 81 100 121
41 / 46
Iterators Generators
Generators
Application: Sieve of Erastothenes
Definition1
In mathematics, the sieve of Erastosthenes is a simple, ancient
algorithm for finding all prime numbers up to any given limit.
It does so by iteratively marking as composite (i.e., not prime) the
multiples of each prime, starting with the first prime number, 2.
The multiples of a given prime are generated as a sequence of
numbers starting from that prime, with constant difference
between them that is equal to that prime.
1
https://en.wikipedia.org/wiki/Sieve of Eratosthenes
42 / 46
Iterators Generators
Generators
Sieve of Erastothenes: Animation
43 / 46
Iterators Generators
Generators
Functions of Iterators
44 / 46
Iterators Generators
Generators
A Generator for the Sieve
def gen_primes(N):
"""Generate primes up to N"""
primes = set()
for n in range(2, N+1):
if all(n % p > 0 for p in primes):
primes.add(n)
yield n
print(list(gen_primes(100)))
45 / 46
Iterators Generators
Generators
A Generator for the Sieve
46 / 46
Iterators Generators
Generators
A Generator for the Sieve
import itertools
def gen_primes():
"""Generate primes one at a time"""
primes = set()
for n in itertools.count(start=2): #default step is 1
if all(n % p > 0 for p in primes):
primes.add(n)
yield n
46 / 46
Floating-Point Numbers
Programming Fundamentals 1
Lesson 10
Pierre Kelsen
2017
1 / 45
Floating-Point Numbers
Outline
Floating-Point Numbers
2 / 45
Floating-Point Numbers
Floating-Point Numbers
Numeric Types
3 / 45
Floating-Point Numbers
Floating-Point Numbers
Numeric Types
3 / 45
Floating-Point Numbers
Floating-Point Numbers
Numeric Types
3 / 45
Floating-Point Numbers
Floating-Point Numbers
Numeric Types
3 / 45
Floating-Point Numbers
Floating-Point Numbers
Numeric Types
3 / 45
Floating-Point Numbers
Floating-Point Numbers
Type float
4 / 45
Floating-Point Numbers
Floating-Point Numbers
Precision and Range
5 / 45
Floating-Point Numbers
Floating-Point Numbers
From Decimal to Binary
I For example,
543 = 5 ∗ 102 + 4 ∗ 101 + 3 ∗ 100 = 5 ∗ 100 + 4 ∗ 10 + 3
6 / 45
Floating-Point Numbers
Floating-Point Numbers
From Decimal to Binary(2)
I For example,
1011 = 1 ∗ 23 + 0 ∗ 22 + 1 ∗ 21 + 1 ∗ 20 = 1 ∗ 8 + 0 ∗ 4 + 1 ∗ 2 + 1
= 11 (in decimal)
7 / 45
Floating-Point Numbers
Floating-Point Numbers
Floats in Binary
8 / 45
Floating-Point Numbers
Floating-Point Numbers
Floats in Binary
8 / 45
Floating-Point Numbers
Floating-Point Numbers
Floats in Binary: Example
9 / 45
Floating-Point Numbers
Floating-Point Numbers
Floats in Binary: Example
9 / 45
Floating-Point Numbers
Floating-Point Numbers
Floats in Binary: Example
9 / 45
Floating-Point Numbers
Floating-Point Numbers
Floats in Binary: Example 2
10 / 45
Floating-Point Numbers
Floating-Point Numbers
Floats in Binary: Example 2
10 / 45
Floating-Point Numbers
Floating-Point Numbers
Floats in Binary: Example 2
10 / 45
Floating-Point Numbers
Floating-Point Numbers
Need for approximations
2−e = 10 ∗ n
I Why is this not possible for integer n?
11 / 45
Floating-Point Numbers
Floating-Point Numbers
Need for approximations
2−e = 10 ∗ n
I Why is this not possible for integer n?
I Because the left side cannot be a multiple of 5
I We conclude that Python often needs to approximate real
numbers (even simple ones)
11 / 45
Floating-Point Numbers
Floating-Point Numbers
Testing Python Implementation
12 / 45
Floating-Point Numbers
Floating-Point Numbers
Testing Python Implementation
12 / 45
Floating-Point Numbers
Floating-Point Numbers
Testing Python Implementation
12 / 45
Floating-Point Numbers
Floating-Point Numbers
Testing Python Implementation
12 / 45
Floating-Point Numbers
Floating-Point Numbers
Testing Python Implementation (2)
I Consider the following code:
x = 0.0
for i in range(10):
x += 0.1
if x == 1.0:
print(x, '= 1.0')
else:
print(x, 'is not 1.0')
I What is the output?
I DEMO.
I Does not recognize equality. Why?
13 / 45
Floating-Point Numbers
Floating-Point Numbers
Testing Python Implementation (2)
I Consider the following code:
x = 0.0
for i in range(10):
x += 0.1
if x == 1.0:
print(x, '= 1.0')
else:
print(x, 'is not 1.0')
I What is the output?
I DEMO.
I Does not recognize equality. Why?
I At some point in the loop it ran out of significant digits and
produced some rounding error
13 / 45
Floating-Point Numbers
Floating-Point Numbers
Testing Python Implementation (3)
14 / 45
Floating-Point Numbers
Floating-Point Numbers
Testing Python Implementation (3)
14 / 45
Floating-Point Numbers
Floating-Point Numbers
Testing Equality
15 / 45
Floating-Point Numbers
Floating-Point Numbers
Testing Equality
15 / 45
Floating-Point Numbers
Floating-Point Numbers
Testing Equality
15 / 45
Floating-Point Numbers
Floating-Point Numbers
Polynomials
16 / 45
Floating-Point Numbers
Floating-Point Numbers
Polynomials
16 / 45
Floating-Point Numbers
Floating-Point Numbers
Polynomials
16 / 45
Floating-Point Numbers
Floating-Point Numbers
Polynomials
16 / 45
Floating-Point Numbers
Floating-Point Numbers
Polynomials
16 / 45
Floating-Point Numbers
Floating-Point Numbers
Polynomials
16 / 45
Floating-Point Numbers
Floating-Point Numbers
Roots of Polynomials
17 / 45
Floating-Point Numbers
Floating-Point Numbers
Roots of Polynomials
17 / 45
Floating-Point Numbers
Floating-Point Numbers
Roots of Polynomials
17 / 45
Floating-Point Numbers
Floating-Point Numbers
Computing Roots
18 / 45
Floating-Point Numbers
Floating-Point Numbers
Computing Roots
18 / 45
Floating-Point Numbers
Floating-Point Numbers
Computing Roots
18 / 45
Floating-Point Numbers
Floating-Point Numbers
Computing Roots
18 / 45
Floating-Point Numbers
Floating-Point Numbers
Computing Roots
18 / 45
Floating-Point Numbers
Floating-Point Numbers
Computing Roots (2)
19 / 45
Floating-Point Numbers
Floating-Point Numbers
Computing Roots (2)
19 / 45
Floating-Point Numbers
Floating-Point Numbers
Computing Roots (2)
19 / 45
Floating-Point Numbers
Floating-Point Numbers
An Example
p(x) = x 5 + x − 1
20 / 45
Floating-Point Numbers
Floating-Point Numbers
An Example
p(x) = x 5 + x − 1
20 / 45
Floating-Point Numbers
Floating-Point Numbers
An Example
p(x) = x 5 + x − 1
20 / 45
Floating-Point Numbers
Floating-Point Numbers
Looking up the Answer
21 / 45
Floating-Point Numbers
Floating-Point Numbers
A Nave Method
22 / 45
Floating-Point Numbers
Floating-Point Numbers
A Nave Method
22 / 45
Floating-Point Numbers
Floating-Point Numbers
A Nave Method
b = 0.0
step = 10**-6
while b**5 + b - 1 < 0:
b += step # same as: b= b+step
22 / 45
Floating-Point Numbers
Floating-Point Numbers
Drawback of Nave Method
23 / 45
Floating-Point Numbers
Floating-Point Numbers
Drawback of Nave Method
23 / 45
Floating-Point Numbers
Floating-Point Numbers
Another method?
24 / 45
Floating-Point Numbers
Floating-Point Numbers
Another method?
24 / 45
Floating-Point Numbers
Floating-Point Numbers
Another method?
24 / 45
Floating-Point Numbers
Floating-Point Numbers
Bisection Search
p = lambda x: x**5+x-1
epsilon = 10**(-6)
low = 0
high = 1
b = 0.5
while high-low >epsilon:
if p(b)<0:
low = b #search interval [b,high]
else:
high = b # #search interval [low,b]
b = (low+high)/2
print(b)
25 / 45
Floating-Point Numbers
Floating-Point Numbers
Complexity of Bisection Search
I How many iterations does the bisection search need?
26 / 45
Floating-Point Numbers
Floating-Point Numbers
Complexity of Bisection Search
I How many iterations does the bisection search need?
I After each iteration the interval to search is halved
I The initial size of the interval is 1 and the final one at most
epsilon
I If k is the required number of iterations for the bisection
1
search, then it suffices that 21k < epsilon or 2k > epsilon
I Taking logarithms in base 2 on both sides we get
1
k > log ( ) = − log(epsilon)
epsilon
I Assuming epsilon = 10−p then
k = − log(10−p ) = p log 10 < 4p iterations would be
sufficient (versus 10p for the linear search)
26 / 45
Floating-Point Numbers
Floating-Point Numbers
How to Find Roots?
I We have seen that bisection search can be quite fast
I it relies however on having an initial search interval
I Does there exist a method that is even faster?
27 / 45
Floating-Point Numbers
Floating-Point Numbers
How to Find Roots?
I We have seen that bisection search can be quite fast
I it relies however on having an initial search interval
I Does there exist a method that is even faster?
27 / 45
Floating-Point Numbers
Floating-Point Numbers
How to Find Roots?
I We have seen that bisection search can be quite fast
I it relies however on having an initial search interval
I Does there exist a method that is even faster?
27 / 45
Floating-Point Numbers
Floating-Point Numbers
Newton’s Method
28 / 45
Floating-Point Numbers
Floating-Point Numbers
Newton’s Method
28 / 45
Floating-Point Numbers
Floating-Point Numbers
Application of Newton’s Method
b5 + b − 1
b−
5 ∗ b4 + 1
should be an even better approximation
1
Note that the denominator is the derivative of the numerator
29 / 45
Floating-Point Numbers
Floating-Point Numbers
Computing the Next Approximation
p = lambda x: x**5+x-1
p2 = lambda x: 5*x**4+1 # derivative of p
def nextVal(b):
'''Assumes float b is an approximation to a root of p
Returns the next approximation (using Newton's method)''
return b-p(b)/p2(b)
30 / 45
Floating-Point Numbers
Floating-Point Numbers
Computing a Root
I DEMO
31 / 45
Floating-Point Numbers
Floating-Point Numbers
Comparing Complexities
32 / 45
Floating-Point Numbers
Floating-Point Numbers
Comparing Complexities
32 / 45
Floating-Point Numbers
Floating-Point Numbers
Comparing Complexities
32 / 45
Floating-Point Numbers
Floating-Point Numbers
Modified Bisection Search
33 / 45
Floating-Point Numbers
Floating-Point Numbers
Comparing Functions
I Let
I bisect denote the function that computes the root using the
modified bisection search
I newt denote the function that computes the root using
Newton’s method
I We assume that both functions have epsilon as argument
(rather than having it as a local variable)
34 / 45
Floating-Point Numbers
Floating-Point Numbers
Running the experiments
35 / 45
Floating-Point Numbers
Floating-Point Numbers
Running the experiments
35 / 45
Floating-Point Numbers
Floating-Point Numbers
The timeit module
36 / 45
Floating-Point Numbers
Floating-Point Numbers
The timeit Function: Example
import timeit
import math
for i in range(10):
statement = 'math.sqrt('+str(i)+')'
print(timeit.timeit(statement, number =1, globals = globals()))
37 / 45
Floating-Point Numbers
Floating-Point Numbers
Timing the Root Finding Functions
I The following code times functions bisect and newt for values
of epsilon 10−2 , . . . , 10−10
I We assume each function is in a module with the same name
import timeit
import math
import bisect
import newt
for epsilon in [10**-i for i in range(2,11)]:
statement1 = 'bisect.bisect('+str(epsilon)+')'
statement2 = 'newt.newt('+str(epsilon)+')'
print(timeit.timeit(statement1, number =1,globals = globals()),'/',
timeit.timeit(statement2, number =1, globals = globals()))
38 / 45
Floating-Point Numbers
Floating-Point Numbers
Timing the Root Finding Functions
39 / 45
Floating-Point Numbers
Floating-Point Numbers
Timing the Root Finding Functions
Floating-Point Numbers
Python Decimal Module
40 / 45
Floating-Point Numbers
Floating-Point Numbers
Floating Point Standards
41 / 45
Floating-Point Numbers
Floating-Point Numbers
Constructing Decimals
42 / 45
Floating-Point Numbers
Floating-Point Numbers
Constructing Decimals
42 / 45
Floating-Point Numbers
Floating-Point Numbers
Constructing Decimals
42 / 45
Floating-Point Numbers
Floating-Point Numbers
Constructing Decimals
42 / 45
Floating-Point Numbers
Floating-Point Numbers
Constructing Decimals
42 / 45
Floating-Point Numbers
Floating-Point Numbers
Constructing Decimals
42 / 45
Floating-Point Numbers
Floating-Point Numbers
Constructing Decimals
42 / 45
Floating-Point Numbers
Floating-Point Numbers
Constructing Decimals
42 / 45
Floating-Point Numbers
Floating-Point Numbers
Constructing Decimals
42 / 45
Floating-Point Numbers
Floating-Point Numbers
Context
I The context for arithmetic is an environment specifying
precision, rounding rules, limits on exponents, flags indicating
the results of operations, and trap enablers which determine
whether signals are treated as exceptions
I DEMO
I >>> from decimal import getcontext
43 / 45
Floating-Point Numbers
Floating-Point Numbers
Context
I The context for arithmetic is an environment specifying
precision, rounding rules, limits on exponents, flags indicating
the results of operations, and trap enablers which determine
whether signals are treated as exceptions
I DEMO
I >>> from decimal import getcontext
I >>> getcontext()
43 / 45
Floating-Point Numbers
Floating-Point Numbers
Context
I The context for arithmetic is an environment specifying
precision, rounding rules, limits on exponents, flags indicating
the results of operations, and trap enablers which determine
whether signals are treated as exceptions
I DEMO
I >>> from decimal import getcontext
I >>> getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN,
Emin=-999999, Emax=999999, capitals=1,
clamp=0, flags=[],
traps=[InvalidOperation, DivisionByZero, Overflow])
I We can modify parameters in the context, e.g.,
I >>> getcontext().prec =6
I sets the precision to 6 (for arithmetic operations)
43 / 45
Floating-Point Numbers
Floating-Point Numbers
Precision
44 / 45
Floating-Point Numbers
Floating-Point Numbers
Precision
44 / 45
Floating-Point Numbers
Floating-Point Numbers
Precision
44 / 45
Floating-Point Numbers
Floating-Point Numbers
Precision
44 / 45
Floating-Point Numbers
Floating-Point Numbers
Precision
44 / 45
Floating-Point Numbers
Floating-Point Numbers
Mixing Floats and Decimals
45 / 45
Floating-Point Numbers
Floating-Point Numbers
Mixing Floats and Decimals
45 / 45
Floating-Point Numbers
Floating-Point Numbers
Mixing Floats and Decimals
45 / 45
Floating-Point Numbers
Floating-Point Numbers
Mixing Floats and Decimals
45 / 45
Matplotlib NumPy Pandas
Programming Fundamentals 1
Lesson 11
Pierre Kelsen
2017
1 / 52
Matplotlib NumPy Pandas
Outline
Matplotlib
NumPy
Pandas
2 / 52
Matplotlib NumPy Pandas
Matplotlib
What is Matplotlib?
3 / 52
Matplotlib NumPy Pandas
Matplotlib
What is PyLab?
4 / 52
Matplotlib NumPy Pandas
Matplotlib
PyLab: Example 1
import pylab
5 / 52
Matplotlib NumPy Pandas
Matplotlib
PyLab: Figure 1
I Explain figure
6 / 52
Matplotlib NumPy Pandas
Matplotlib
Saving Figures
7 / 52
Matplotlib NumPy Pandas
Matplotlib
Saving Figures
import pylab
7 / 52
Matplotlib NumPy Pandas
Matplotlib
Current Figure
8 / 52
Matplotlib NumPy Pandas
Matplotlib
Another Example
import pylab
principal = 1000 # initial investment
interest = 0.05
years = 20
values = []
for i in range(years+1):
values.append(principal)
principal += principal*interest
pylab.plot(values)
pylab.show()
Matplotlib
Plot
10 / 52
Matplotlib NumPy Pandas
Matplotlib
Informative Labeling
11 / 52
Matplotlib NumPy Pandas
Matplotlib
Plot #2
12 / 52
Matplotlib NumPy Pandas
Matplotlib
Finding the Roots
13 / 52
Matplotlib NumPy Pandas
Matplotlib
Finding the Roots (2)
14 / 52
Matplotlib NumPy Pandas
Matplotlib
Finding the Roots (2)
import pylab
14 / 52
Matplotlib NumPy Pandas
Matplotlib
Finding the Roots (3)
I The value of the root still a bit hard to determine
I What would help?
15 / 52
Matplotlib NumPy Pandas
Matplotlib
Finding the Roots (3)
I The value of the root still a bit hard to determine
I What would help?
I drawing a horizontal line y=0
I we can simply draw it on top of the current figure (see code
below)
import pylab
15 / 52
Matplotlib NumPy Pandas
Matplotlib
Finding the Roots (3)
I The value of the root still a bit hard to determine
I What would help?
I drawing a horizontal line y=0
I we can simply draw it on top of the current figure (see code
below)
import pylab
NumPy
What is NumPy?
16 / 52
Matplotlib NumPy Pandas
NumPy
A First Example
17 / 52
Matplotlib NumPy Pandas
NumPy
Applying Operators
18 / 52
Matplotlib NumPy Pandas
NumPy
Applying Operators
18 / 52
Matplotlib NumPy Pandas
NumPy
Applying Operators
19 / 52
Matplotlib NumPy Pandas
NumPy
Applying Operators
19 / 52
Matplotlib NumPy Pandas
NumPy
Applying Operators
19 / 52
Matplotlib NumPy Pandas
NumPy
Matrix Operations
20 / 52
Matplotlib NumPy Pandas
NumPy
Matrix Operations
20 / 52
Matplotlib NumPy Pandas
NumPy
Matrix Operations (2)
21 / 52
Matplotlib NumPy Pandas
NumPy
Matrix Operations (2)
21 / 52
Matplotlib NumPy Pandas
NumPy
Matrix Operations (2)
21 / 52
Matplotlib NumPy Pandas
NumPy
Matrix Operations (2)
21 / 52
Matplotlib NumPy Pandas
Pandas
What is Pandas?
22 / 52
Matplotlib NumPy Pandas
Pandas
A First Example
I Output:
23 / 52
Matplotlib NumPy Pandas
Pandas
A First Example
I Output:
label value
0 A 1
1 B 2
2 C 3
3 A 4
4 B 5
5 C 6
23 / 52
Matplotlib NumPy Pandas
Pandas
A More Interesting Example
1
http://pythonforengineers.com/introduction-to-pandas/
24 / 52
Matplotlib NumPy Pandas
Pandas
Inspecting the Data
25 / 52
Matplotlib NumPy Pandas
Pandas
Loading the Data
I The data can be read with the read csv function of pandas
import pandas as pd
data = pd.read_csv('hubble_data.csv')
I What type is data?
26 / 52
Matplotlib NumPy Pandas
Pandas
Loading the Data
I The data can be read with the read csv function of pandas
import pandas as pd
data = pd.read_csv('hubble_data.csv')
I What type is data?
I It’s a DataFrame.
I We can print the first five rows of the DataFrame like this:
data.head() → DEMO
I The top row is the header
I If the csv file has no headers, we can pass them (as a list of
strings) as second argument to the read csv function
26 / 52
Matplotlib NumPy Pandas
Pandas
Viewing a Column
27 / 52
Matplotlib NumPy Pandas
Pandas
Viewing a Column
27 / 52
Matplotlib NumPy Pandas
Pandas
Plotting
28 / 52
Matplotlib NumPy Pandas
Pandas
Fixing the Plot
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('hubble_data.csv')
data.set_index('distance',inplace = True)
data.plot()
plt.show()
I DEMO
29 / 52
Matplotlib NumPy Pandas
Pandas
Data Analysis
import pandas as pd
import numpy as np
# reading the data
wh = pd.read_csv('wh_data.csv', index_col=0)
2
https://www.dataquest.io/blog/pandas-pivot-table/
30 / 52
Matplotlib NumPy Pandas
Pandas
Looking at the data
31 / 52
Matplotlib NumPy Pandas
Pandas
Info on the DataFrame
32 / 52
Matplotlib NumPy Pandas
Pandas
Info on the DataFrame
32 / 52
Matplotlib NumPy Pandas
Pandas
Info on the DataFrame
33 / 52
Matplotlib NumPy Pandas
Pandas
Info on the DataFrame
33 / 52
Matplotlib NumPy Pandas
Pandas
Calculating Happiness Score
34 / 52
Matplotlib NumPy Pandas
Pandas
Some Statistical information
35 / 52
Matplotlib NumPy Pandas
Pandas
Some Statistical information
35 / 52
Matplotlib NumPy Pandas
Pandas
Some Statistical Terms
36 / 52
Matplotlib NumPy Pandas
Pandas
Some Statistical Terms
36 / 52
Matplotlib NumPy Pandas
Pandas
Missing Values
37 / 52
Matplotlib NumPy Pandas
Pandas
Missing Values
37 / 52
Matplotlib NumPy Pandas
Pandas
Missing Values
37 / 52
Matplotlib NumPy Pandas
Pandas
Pivot Table
I We will use pivot tables to get more insight into the data
Definition3
A pivot table is a table that summarizes data in another table, and
is made by applying an operation such as sorting, averaging, or
summing to data in the first table, typically including grouping of
the data.
3
https://en.wikipedia.org/wiki/Pivot table
38 / 52
Matplotlib NumPy Pandas
Pandas
Our First Pivot Table
39 / 52
Matplotlib NumPy Pandas
Pandas
Our First Pivot Table
Happiness Score
Year
2015 5.375734
2016 5.382185
2017 5.354019
39 / 52
Matplotlib NumPy Pandas
Pandas
Interpreting the Output
40 / 52
Matplotlib NumPy Pandas
Pandas
Ranking by Region
41 / 52
Matplotlib NumPy Pandas
Pandas
Ranking by Region
Happiness Score
Region
Australia and New Zealand 7.302500
Central and Eastern Europe 5.371184
Eastern Asia 5.632333
Latin America and Caribbean 6.069074
Middle East and Northern Africa 5.387879
North America 7.227167
Southeastern Asia 5.364077
Southern Asia 4.590857
Sub-Saharan Africa 4.150957
Western Europe 6.693000
41 / 52
Matplotlib NumPy Pandas
Pandas
Multi-Index Pivot Tables
I Suppose we want to know the average happiness score by
region and year
I We can simply pass both column names as indices
>>> pd.pivot_table(wh, index = ['Region', 'Year'],
values = "Happiness Score")
(Only showing top 12 rows)
42 / 52
Matplotlib NumPy Pandas
Pandas
Multi-Index Pivot Tables
I Suppose we want to know the average happiness score by
region and year
I We can simply pass both column names as indices
>>> pd.pivot_table(wh, index = ['Region', 'Year'],
values = "Happiness Score")
(Only showing top 12 rows)
42 / 52
Matplotlib NumPy Pandas
Pandas
Columns Parameter
I Using the columns parameter we can improve the readability
of the previous table
>>> pd.pivot_table(wh, index = 'Region', columns = 'Year', values = "Happiness Score")
43 / 52
Matplotlib NumPy Pandas
Pandas
Columns Parameter
I Using the columns parameter we can improve the readability
of the previous table
>>> pd.pivot_table(wh, index = 'Region', columns = 'Year', values = "Happiness Score")
Pandas
Columns Parameter (2)
44 / 52
Matplotlib NumPy Pandas
Pandas
Aggregation Functions
45 / 52
Matplotlib NumPy Pandas
Pandas
Custom Aggregation Functions
46 / 52
Matplotlib NumPy Pandas
Pandas
Custom Aggregation Functions
46 / 52
Matplotlib NumPy Pandas
Pandas
Custom Categorization
I So far we have categorized the data according to the
categories present in the original data
I Using string search we can do more flexible categorization
I Suppose we want to group data by continent
I We can do this as follows
>>> t = pd.pivot_table(wh, index = 'Region', values="Happiness Score",
aggfunc= [np.mean])
>>> t[t.index.str.contains('Asia')]
47 / 52
Matplotlib NumPy Pandas
Pandas
Custom Categorization
I So far we have categorized the data according to the
categories present in the original data
I Using string search we can do more flexible categorization
I Suppose we want to group data by continent
I We can do this as follows
>>> t = pd.pivot_table(wh, index = 'Region', values="Happiness Score",
aggfunc= [np.mean])
>>> t[t.index.str.contains('Asia')]
mean
Happiness Score
Region
Eastern Asia 5.632333
Southeastern Asia 5.364077
Southern Asia 4.590857
47 / 52
Matplotlib NumPy Pandas
Pandas
Extracting Data
48 / 52
Matplotlib NumPy Pandas
Pandas
Extracting Data
mean
Happiness Score
Region Year
Middle East and Northern Africa 2015 5.406900
2017 5.369684
Sub-Saharan Africa 2015 4.202800
2017 4.111949
48 / 52
Matplotlib NumPy Pandas
Pandas
Handling Missing Data
49 / 52
Matplotlib NumPy Pandas
Pandas
Handling Missing Data (2)
50 / 52
Matplotlib NumPy Pandas
Pandas
Handling Missing Data (2)
I The following code splits our data into 4 quantiles:
score = pd.qcut(wh["Happiness Score"], 4)
pd.pivot_table(wh, index= ['Region', score], values= "Happiness Score",
aggfunc= 'count').head(9)
51 / 52
Matplotlib NumPy Pandas
Pandas
Handling Missing Data (2)
I The following code splits our data into 4 quantiles:
score = pd.qcut(wh["Happiness Score"], 4)
pd.pivot_table(wh, index= ['Region', score], values= "Happiness Score",
aggfunc= 'count').head(9)
Happiness Score
Region Happiness Score
Australia and New Zealand (2.692, 4.509] NaN
(4.509, 5.283] NaN
(5.283, 6.234] NaN
(6.234, 7.587] 6.0
Central and Eastern Europe (2.692, 4.509] 10.0
(4.509, 5.283] 28.0
(5.283, 6.234] 46.0
(6.234, 7.587] 3.0
Eastern Asia (2.692, 4.509] NaN
51 / 52
Matplotlib NumPy Pandas
Pandas
Handling Missing Data (2)
I A NaN in the last column really means that no row is in this
quantile
I It thus makes more sense to replace NaN by 0
score = pd.qcut(data["Happiness Score"], 3)
pd.pivot_table(wh, index= ['Region', score], values= "Happiness Score",
aggfunc= 'count',fill_value= 0).head(9)
52 / 52
Matplotlib NumPy Pandas
Pandas
Handling Missing Data (2)
I A NaN in the last column really means that no row is in this
quantile
I It thus makes more sense to replace NaN by 0
score = pd.qcut(data["Happiness Score"], 3)
pd.pivot_table(wh, index= ['Region', score], values= "Happiness Score",
aggfunc= 'count',fill_value= 0).head(9)
Happiness Score
Region Happiness Score
Australia and New Zealand (2.692, 4.509] 0
(4.509, 5.283] 0
(5.283, 6.234] 0
(6.234, 7.587] 6
Central and Eastern Europe (2.692, 4.509] 10
(4.509, 5.283] 28
(5.283, 6.234] 46
(6.234, 7.587] 3
Eastern Asia (2.692, 4.509] 0 52 / 52
Software Engineering
Programming Fundamentals 1
Lesson 12
Pierre Kelsen
2017
1 / 53
Software Engineering
Outline
Software Engineering
2 / 53
Software Engineering
Software Engineering
Software vs Programs
3 / 53
Software Engineering
Software Engineering
Software vs Programs
3 / 53
Software Engineering
Software Engineering
Software vs Programs
3 / 53
Software Engineering
Software Engineering
Software vs Programs (2)
4 / 53
Software Engineering
Software Engineering
Software Engineering
Definition1
Software Engineering is the set of techniques - including theories,
methods, processes, tools and languages - for developing and
operating production software meeting defined standards of quality.
Production software is operational software, intended to function
in real environments to solve real problems.
1
Bertrand Meyer, Touch of Class, Springer, 2009
5 / 53
Software Engineering
Software Engineering
Production Software
6 / 53
Software Engineering
Software Engineering
Challenges of Software Engineering
7 / 53
Software Engineering
Software Engineering
Software Quality
8 / 53
Software Engineering
Software Engineering
Software Quality
8 / 53
Software Engineering
Software Engineering
Product Quality
9 / 53
Software Engineering
Software Engineering
Product Quality
9 / 53
Software Engineering
Software Engineering
Product Quality
9 / 53
Software Engineering
Software Engineering
Product Quality
9 / 53
Software Engineering
Software Engineering
Product Quality
9 / 53
Software Engineering
Software Engineering
Product Quality
9 / 53
Software Engineering
Software Engineering
Product Quality
10 / 53
Software Engineering
Software Engineering
Product Quality
10 / 53
Software Engineering
Software Engineering
Product Quality
10 / 53
Software Engineering
Software Engineering
Product Quality
10 / 53
Software Engineering
Software Engineering
Product Quality
11 / 53
Software Engineering
Software Engineering
Product Quality
11 / 53
Software Engineering
Software Engineering
Product Quality
11 / 53
Software Engineering
Software Engineering
Product Quality
11 / 53
Software Engineering
Software Engineering
Product Quality
11 / 53
Software Engineering
Software Engineering
Product Quality
12 / 53
Software Engineering
Software Engineering
Product Quality
12 / 53
Software Engineering
Software Engineering
Product Quality
12 / 53
Software Engineering
Software Engineering
Product Quality
12 / 53
Software Engineering
Software Engineering
Product Quality
12 / 53
Software Engineering
Software Engineering
Product Quality
12 / 53
Software Engineering
Software Engineering
Product Quality
12 / 53
Software Engineering
Software Engineering
Product Quality
12 / 53
Software Engineering
Software Engineering
Product Quality
12 / 53
Software Engineering
Software Engineering
Internal vs External Quality Factors
13 / 53
Software Engineering
Software Engineering
Internal vs External Quality Factors
13 / 53
Software Engineering
Software Engineering
Process Quality
I Process Qualities
I Production speed:
14 / 53
Software Engineering
Software Engineering
Process Quality
I Process Qualities
I Production speed: ability to deliver the software quickly
14 / 53
Software Engineering
Software Engineering
Process Quality
I Process Qualities
I Production speed: ability to deliver the software quickly
I Cost effectiveness:
14 / 53
Software Engineering
Software Engineering
Process Quality
I Process Qualities
I Production speed: ability to deliver the software quickly
I Cost effectiveness: how many resources does the development
consume? Main component is usually personnel costs which
can be expressed in person-months
14 / 53
Software Engineering
Software Engineering
Process Quality
I Process Qualities
I Production speed: ability to deliver the software quickly
I Cost effectiveness: how many resources does the development
consume? Main component is usually personnel costs which
can be expressed in person-months
I Collaboration effectiveness:
14 / 53
Software Engineering
Software Engineering
Process Quality
I Process Qualities
I Production speed: ability to deliver the software quickly
I Cost effectiveness: how many resources does the development
consume? Main component is usually personnel costs which
can be expressed in person-months
I Collaboration effectiveness: effectiveness of developers working
together
14 / 53
Software Engineering
Software Engineering
Process Quality (2)
15 / 53
Software Engineering
Software Engineering
Process Quality (2)
15 / 53
Software Engineering
Software Engineering
Process Quality (2)
15 / 53
Software Engineering
Software Engineering
Process Quality (2)
15 / 53
Software Engineering
Software Engineering
Software Development Activities
16 / 53
Software Engineering
Software Engineering
Software Development Activities
16 / 53
Software Engineering
Software Engineering
Software Development Activities
16 / 53
Software Engineering
Software Engineering
Software Development Activities(2)
I Requirements analysis
I Defines the requirements of the system
I Both functional and non-functional requirements need to be
described
I Functional requirements: what is the system able to do?
I Non-functional requirements: have to do with how the system
should operate. Examples?
17 / 53
Software Engineering
Software Engineering
Software Development Activities(2)
I Requirements analysis
I Defines the requirements of the system
I Both functional and non-functional requirements need to be
described
I Functional requirements: what is the system able to do?
I Non-functional requirements: have to do with how the system
should operate. Examples?
I E.g., Performance needs to reach a certain level
I Software needs to integrate with existing system
I Constraints on the choice of technologies
I Given levels of security and reliability
17 / 53
Software Engineering
Software Engineering
Software Development Activities(3)
I Specification
I Precise description of individual elements of the system
I Difference between specification and requirement analyses?
18 / 53
Software Engineering
Software Engineering
Software Development Activities(3)
I Specification
I Precise description of individual elements of the system
I Difference between specification and requirement analyses?
I Requirements are customer-oriented, Specification is
developer-oriented
I Difference in the amount of rigour and formalism (higher for
specification document)
18 / 53
Software Engineering
Software Engineering
Software Development Activities(4)
I Design
I Builds the overall architecture of the system
I Defines the different parts/modules as well as their interaction
I Implementation: the actual programming of the system
I Can be model-driven: code generation from models may
automate parts of the coding process
19 / 53
Software Engineering
Software Engineering
Software Development Activities(5)
I Documentation
I Documents the software system - for customers and developers
I Documents the software process
I Maybe partly automated
I Verification & Validation (V&V)
I Making sure the systems does the right things in the right way
20 / 53
Software Engineering
Software Engineering
Lifecycle Models
I Lifecycle models address the question of how the above
activities should be organized (eg, in what sequence)
21 / 53
Software Engineering
Software Engineering
Lifecycle Models
I Lifecycle models address the question of how the above
activities should be organized (eg, in what sequence)
I Waterfall model is the traditional way to organize the
activities
I based on executing the above activities in the order given
21 / 53
Software Engineering
Software Engineering
About the Waterfall Model
22 / 53
Software Engineering
Software Engineering
About the Waterfall Model
22 / 53
Software Engineering
Software Engineering
The Spiral Model
23 / 53
Software Engineering
Software Engineering
About the Spiral Model
24 / 53
Software Engineering
Software Engineering
Agile Development
25 / 53
Software Engineering
Software Engineering
Requirements Engineering
26 / 53
Software Engineering
Software Engineering
A Standard for Requirements Engineering
27 / 53
Software Engineering
Software Engineering
Scope of Requirements
28 / 53
Software Engineering
Software Engineering
Obtaining Requirements
29 / 53
Software Engineering
Software Engineering
The glossary
30 / 53
Software Engineering
Software Engineering
The glossary
30 / 53
Software Engineering
Software Engineering
Twelve Properties of Good Requirements
31 / 53
Software Engineering
Software Engineering
Property 1: Justification
32 / 53
Software Engineering
Software Engineering
Property 1: Justification
32 / 53
Software Engineering
Software Engineering
Property 2: Correctness
33 / 53
Software Engineering
Software Engineering
Property 2: Correctness
33 / 53
Software Engineering
Software Engineering
Property 3: Completeness
34 / 53
Software Engineering
Software Engineering
Property 3: Completeness
34 / 53
Software Engineering
Software Engineering
Property 4: Consistency
35 / 53
Software Engineering
Software Engineering
Property 4: Consistency
35 / 53
Software Engineering
Software Engineering
Property 5: Unambiguous
36 / 53
Software Engineering
Software Engineering
Property 5: Unambiguous
36 / 53
Software Engineering
Software Engineering
Property 6: Feasability
37 / 53
Software Engineering
Software Engineering
Property 6: Feasability
37 / 53
Software Engineering
Software Engineering
Property 7: Verifiability
38 / 53
Software Engineering
Software Engineering
Property 7: Verifiability
38 / 53
Software Engineering
Software Engineering
Property 7: Verifiability
38 / 53
Software Engineering
Software Engineering
Property 8: Interfaced
39 / 53
Software Engineering
Software Engineering
Property 9: Priorities
40 / 53
Software Engineering
Software Engineering
Property 9: Priorities
40 / 53
Software Engineering
Software Engineering
Property 10: Understandability
41 / 53
Software Engineering
Software Engineering
Property 11: Endorsement
42 / 53
Software Engineering
Software Engineering
Verification and Validation
43 / 53
Software Engineering
Software Engineering
Verification and Validation
43 / 53
Software Engineering
Software Engineering
Design and Code Reviews
44 / 53
Software Engineering
Software Engineering
Design and Code Reviews (2)
45 / 53
Software Engineering
Software Engineering
Design and Code Reviews (2)
45 / 53
Software Engineering
Software Engineering
Static Analysis
46 / 53
Software Engineering
Software Engineering
Suspicious Code Patterns
47 / 53
Software Engineering
Software Engineering
Completeness of V&V Techniques
48 / 53
Software Engineering
Software Engineering
Completeness of V&V Techniques
48 / 53
Software Engineering
Software Engineering
Program Proving
49 / 53
Software Engineering
Software Engineering
Other Static Techniques
50 / 53
Software Engineering
Software Engineering
Model Checking
51 / 53
Software Engineering
Software Engineering
Abstract Interpretation
52 / 53
Software Engineering
Software Engineering
Abstract Interpretation
52 / 53
Software Engineering
Software Engineering
The End
53 / 53