PF1 Pedro Synthesis
PF1 Pedro Synthesis
PF1 Pedro Synthesis
Miller's law
The Miller's law says that the average that a person can keeè in working memory is
seven +-2
What is a problem?
A problem can be subdivided in 2 parts:
The problem input: can include some restrictions
The problem output: emphasizes the relation between input and output
Imperative knowledge
Imperative knowledge is a sequence of instructions, called a program, where
these instructions are understandable by a computer.
What is an algorithm?
An algorithm is a finite sequence of well-defined computer-implementable
instructions, typically to solve a class of problems or to perform a
computation.
What is a program?
A program consists in a sequence of instructions.
What is abstraction?
Abstraction is the process of removing physical, spatial, or temporal details
in the study of objects or systems to focus attention on details of greater
importance.
Further facts
Python is an interpreted language. This means that the instructions are
executed directly, or in others words it doesn't need to be compiled first.
Python is a dynamically typed language. This means that the correctness of
types can generally onle be checked at runtime. (eg: no need to specify the
type of an integer like in java)
Python Shell
Python shell is the basic way to use Python, as it runs in the terminal window.
This allows for iteractively execute Python instructions. The disadvante is
that it has no support for saving code.
IDLE
IDLE is an Integrated Developement and Learning Environment which is an IDE
that comes with Python. The IDLE also inlcudes the Python shell.
An IDE, Integrated Developement Environment compacts a buch of tools in a
single software to write programs
Syntax
The syntax in Python is a set of rules that determine how a Python program will
be written and interpreted.
Semantics
The semantics of Python associates with each program a meaning. This meaning
can be defined as the behaviour of the interpreter when it executes the
program, which includes the output that is generated.
Errors in Python
There are two types of errors in Python:
The syntax errors: These errors can be caught before the program executes.
The exceptions: These errors occur when the program is running.
Straight-line programs
Straight-line programs are those where the statements are executed after one
another, in the order they occur, until there are no more statements.
Basic if-statements
The if-statement is used for conditional execution
if expression:
statement(s)
elif expression:
statement(s)
....
else:
statement(s)
#example
if x < 00: print('x is negative')
Identation
The statements following an expression form a block and these statements need
to be idented if on sparate line. Once the block is finished, the identation
level returns to that of the preceding clause.
Strings and sequences
About classes
A class is the type of an object. For example for the string object the class
is str.
The main elements of a class are:
data items called instance variables
function called methods
Immutability of strings
x = 'ABC'
x.lower()
In the example above, x.lower returns a copy of the string x. This is because
strings in Python are immutable, meaning their contents cannot be changed.
x = 'Hello'
y = 'world'
x+y = 'Hello world'
membership testing
indexing
slicing
Lists
For more general sequences, we can use the list datatype. Unlike strings, lists
are mutable, meaning that the values can change.
Binary search
Binary search is an algorithm that compares the target value to the middle of
the array. If they are unequal, the half in which the target cannot lie is
eliminated and the search continues on the remaining half until it succeeds. If
the search ends with the remainder being empty, the tartget is not in the
array.
Loop varient
A loop varient is an integer expression E with the following properties:
for an iteration to execute we must have E >= 0
Each iteration of the loop decreases the value E.
Loop invarient
A loop invarient for a loop is the condition that holds before and after each
iteration of a loop.
What would be the complexity of the linear search in the best case?
In the best case the element is found at the first position of the
sequence. Thus the complexity in the best case is independent of the
lenght of the input sequence. We talk about constant complexity.
#Functions in Python
Docstring
Docstring are comments which have the purpose to jelp the programmers and users
to know what the functions do. Usually it contais whar is the input and the
output. The advantage of docstrings id the fact that the user/client don't need
to understand the complexity of the program.
Modules
Definition
A module in Python contains a collection of Python definitions and statements. In
other words, a module is a Python file.
Top-down approach
This approach consitst in breaking the original problem into subproblems, then
break those subproblems in sub subproblems, until the porblem we end-up with is
easy to solve.
Bottom-up approach
This approach consists in working from what's already known to build solutions
to bigger problems.
Recursion
Definition
Recursion is the same as the factorial (eg: n!) in mathematics.
def f(n):
""" Assumes that n is an integer >= 0
Returns n! """
if n == 0:
return 1
else:
return n*f(n-1)
Recursion depth
If we run the factorial function for large numbers we get an exception called
RecursionError, stating that the maximum recursion depth is exceeded.
Interactive solution
We can view the recursive program as a top-down solution for the factorial
function. It is straightforward to develop a bottom-up solution to this
problem.
Possible implementation:
def f(n):
""" Assumes that n is an integer >= 0
Returns n! """
result = 1
for i in range(1, n+1): # from 1 to n
result *= i
return result
A structured type is an item that has an internal structure. Some examples are:
strings (sequence of characters) and lists (sequence of objects).
A non-structured type is an item that has no internal structure, meaning that they
are not further subdivided. Some exmaples are the numeric and boolean types.
Sequences
A sequence is an ordered container of items that can be accessed via an index.
Tuples
A tuple is a sequence type which like a list can contain objects of arbitrary
types. Different from a list, tuples are represented by a comma-separated list of
elemets surrounded by parentheses.
List comprehension
List comprehension provides a way to construct a list out of another list.
Definition
Dictionaries
A _dictionary is a set of key-values pairs. The key and the value are separated ba
a colon (:) and the key-value pairs are separated by a comma.
Fucntions as objects
Functions as arguments
Since functions are objects, we can pass functions as arguments to another
function.
Example
Lambda expressions
A lambda expression is an expression that defines an "anonymous function". The
general form is : lambda : .
Example
lambda x : x*x
Files
Current directory
How to find the location of the current directory?
By using the method getCWD() in the module os.
Exceptions
Standards exeptions
Try statement
try:
statement(s)
except [expression]:
statement(s)
Testing vs debugging
Testing consists in checking the correctness of a program by running it on a
set of inputs.
Debugging consists in finding the error in a program that we know not to be
correct.
Test suite
A test suite is as set of possibel inputs to rest the program.
Black-box testing
Black-box test suites are created without looking ar the code.
Boundary-values technique
This technique consits in examining test cases at the boundary values.
Invalid inputs
There is two approaches when it comes to testing:
contract based testing: only test valid inputs
defensive testing: test all inputs
Testing vs debugging
Testing consists in checking the correctness of a program by running it on a
set of inputs.
Debugging consists in finding the error in a program that we know not to be
correct.
Test suite
A test suite is as set of possibel inputs to rest the program.
Black-box testing
Black-box test suites are created without looking ar the code.
Boundary-values technique
This technique consits in examining test cases at the boundary values.
Invalid inputs
There is two approaches when it comes to testing:
contract based testing: only test valid inputs
defensive testing: test all inputs
Generators
Definition
A generator is a function whos body contains the special keyword yield.
Floating-point numbers
Type float
In Python, ther is no limit to the sizw of integers.
A float can be represented as a pair of integers, where we have:
the significat difits
the exponent
Example
The number 1,949 is represented by 1949 (the significant digits), and -3
(the exponent)
Floats in binary
Floats are internally not represented in decimal but in binary.
About classes
Introduction
Every data item/value in Python is an object whre the type of an object is a class
Class definition
Classes are defined using the class statement. One thing to note is that a class
must be non-empty, thus a minimal class definition could look like this:
class C:
pass #do noting
Classes vs objects
When executing a class statement, this results in the creation of a class where
this class is also an object. The type of this object is the class "type" and
since it is also a class, it is also represented by a class object where the
"type" class object is its own type.
Instances
When an object has type a class C, we also say that the objects is an instance
of class C.
To test if an object x has a type classs object C, we can call the built-in
function **isinstance(x, C).
Encapsulation
Introduction
Encapsulation consists in separating *what needs to be done" from "how its done".
This separation consists of the interface, where the attributs are vusible to
other classes, and the implementation, where the attributes are invisible to the
other classes.
Advantages
More flexibility:
The implementation can be changed without changing the interface
Encapsulation in Python
In Python attributes in the interface are public and those in the implemention
are private
To set an attribute in private, prefix it with double underscore (__x).
Inheritance
Introduction
In Pyton, we can define subclasses of other classes. The syntax is the following:
class C(D): ....; where C is a subclass of D and D is a superclass of C.
Polymorphism
Introduction
Polymorphism relies on two fundamentals mechanims. The method overriding and the
dynamic binding, where the version of the function that is called is only
determined at runtime.
Abstract classes
Abstract classes is a class that has one or more methods that are not
implemented (or is implemented to raise an exception)
Matplotlib
What is malplotlib?
Matplotlib is a library for making 2D plots of arrays in Python
What is Pylab?
Pylab is a module (part of matplotlib) that provides facilities for data
visualization, data analysis and numeric computations-
Example
import pylab
pylab.figure(1) #create figure 1
pylab.plot([1, 2, 2], [1,7,9,5]) #draw on figure 1
pylab.show()
NumPy
What is NumPy
NumPy provides an efficient way to store and manipulate multi-dimensional arrays
in Python.
#Pandas
What is Pandas?
Pandas is built on top of NumPy and it provides a labellled interface to multi-
dimensional data using a DataFrame object.
Pivot table
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 data.