Lecture 2:
- Command-line mode vs script-mode
- Arithmetic operators:
- % modulus
- ** exponential
- // floor division
- Comparison, logical, identity, membership, bitwise operators:
Lecture 4:
- Python function is part of the python script file, whereas methods are defined inside a class definition
- We can call a function directly if it’s in the same module or import a module and then call the function directly. To call a method, we need a class or an object of the class
- Python functions can access all the global variables, whereas Python class methods can access global variables, class attributes, and functions
Lecture 5:
- Module is a smaller library, defined by someone
- Variable+value = an object
- The variable is redefined inside a function doesn’t change the value of the global variable
def f4() :
print(s)
s = "I'm Harry Potter's Friend"
print(s)
s = "I'm Ali Baba's Friend"
f4()
print(s)
- The function f4 is called first without knowing what is s so error found
- The interpreter only read the functions and methods
- If global variable is defined within a function, the global will replace the local
-
Creating your own module:
Lecture 7: String
- Sequences:
- String
- List
- Tuples
- String & string manipulation:
-
String are immutable, all string methods returns another string
-
Lecture 8:
-
Precondition: a condition that must always be true just before the execution of some section of codes or before an operation in a formal specification
- Might or might not work as intended
-
Syntax error: indentation
-
Runtime error: division, incompatible types, using undefined identifier, accessing non-existed elements
-
Semantic error: output is meaningless
- (“my age is cs”)
-
Logical error: output is wrong, unintended
- (“my age is 1”)
-
Breakpoint: use the red dot mark on Pycharm, VScode
-
Assertion and handling exceptions:
-
Assertions: to test the correctness of your code by checking if some specific conditions remain TRUE
- If the assertion condition is false, then the assertion raises an exception and terminates the program’s execution
-
Exception handling:
- A process of responding to the occurrence of exceptions – anomalous or exceptional conditions requiring special processing – during the execution of a program
- try statements run first; if an error mentioned in one except’s arguments happened while running then except’s statements run, else the else statement run then the finally statements always run
- A process of responding to the occurrence of exceptions – anomalous or exceptional conditions requiring special processing – during the execution of a program
-
Lecture 9:
-
Conditionals: if-statements
-
If -else vs nested if-else
Lecture 10: Memory in Python
- Memory is for using data structure
- Memory management:
- Efficiently allocating
- Deallocating
- Coordinating memory
- Memory allocation: allocation of a space (or a block) in the computer memory
- Garbage collector: automatically handles memory allocation and deallocation
- Private heap: contains all Python objects and data structure
- Garbage collection: process which the interpreter frees up the memory (when not in use) to make the available memory for ???
Lecture 11&12: Objects , list & sequences
- List is one of built-in structures; together with tuples, dictionaries, and set
- List are mutable, sequence types
- Identical vs equivalent: is vs ==
- is compare the pointer address
- == compare the value
- Every list is different object from the other list, equivalent but not identical
- a=[1], b = [1] then (a ==b) = True
- a = [1], b = a then they have same pointer address so (a is b) = True
- except 2 empty list ( a=[], b=[] then (a is b) is True)
- Memory:
- A list is a single object
- Each object has the following properties:
- A type
- Value: An internal data representation
- A set of procedures for interaction with the object ( object’s function, a.f())
- An object is an instance of a type
- Enumerate():
- se enumerate to keep track of index and element values: adds a counter to an iterable and returns it in a form of enumerate object.
Lecture 13: iteration and for loops
- Iteration: basic building block to repeat some code until a condition is met
- for-loop: iterating over a sequence (set, string, list, tuple or dictionary)
- Definite iteration: do sth a fixed number of times
- Process each item in a sequence by executing a set of statements, once for each item in the sequence
- For python’s for loop in a range, example: \text{}$${\color{lightpink}\text{for}} \space \text{i}\space {\color{lightpink}\text{in}} \space {\color{yellowgreen}\text{range}} ({\color{lightpink}\text{x}}) generates list and will be iterated through all of its elements so change variable i midway wont affect the number of execution
- Counter and accumulator
Lecture 14: While-Loops and Loop Invariants
- Definite looping variables
- Always checking the condition, either 0 or 1
- Infinite loop: when the condition never becomes false
-
Nested while loop:
- list(range(x)) returns a list = [ 0, 1, 2, 3], so i is assigned to each elements of the list, changing x only change the new list of range for j
Lecture 15: Tuples and dictionaries
-
Tuple:
- another data type, separated by parentheses()
- Immutable
-
Dictionary:
- Mutable data type
- another datatype, each pair separated by curly bracket, key and value separated by colon
- a set of key/value pairs, called entry
- accessed values by key
Lecture 16: Algorithm Design
- Algorithm is a step-by-step procedure which defines a set of instructions to be executed in a certain order to solve problem and get the desired output.
- Independent of underlying language
- Characteristics of algorithms:
- Unambiguous
- Input
- Output
- Finiteness
- Feasibility
- Independent
- Most efficient for a given problem: algorithm with the least execution time
- Factors that affect execution time:
- Amount of data
- Type of hardware
- Programming language and compiler used
- …
- Big-O notation: used to describe the complexity by worse case scenario, how many steps required to execute the algorithm between the inputs. Time = sum of time for all statements
- Constant-time algorithm: O(1) or order 1, no matter the size of input same nb of steps
- for basic operations
- Linear-time complexity: O(n) or order of n
- Logarithm-time complexity: O(log(n))
- O(nlog(n))
- ….
- Constant-time algorithm: O(1) or order 1, no matter the size of input same nb of steps
Lecture 17: Sorting
-
Selection sort: O(n^2)
- First unsorted compared to all the rest, if bigger, swap
-
Merge Sort: O(n*log(n))
- Keep divide the array to 2 subarrays til only 1 item left
-
Quick Sort: O(n^2)
- Choose a pivot number, can be first or last or median; then divides 2 subarrays, one for values bigger than pivot and one for smaller.
-
Insertion sort:
- Pick each item one at a time, and insert it where it is less than the right one and smaller than the left one
Lecture 18: Search
-
Linear search:
- Compare each and every item
-
Binary Search:
- Requires the array to be sorted beforehand
- Begin with the mid element of the whole array as a search key.
- If the value of the search key is equal to the item then return an index of the search key.
- Or if the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.
- Otherwise, narrow it to the upper half.
- Repeatedly check from the second point until the value is found or the interval is empty.
Lecture 19: Recursion
- A methods of solving a problem where the solution depends on solutions to smaller instance of the same problem
- Base Case: stopping condition-case
- Recursive case:
- for a list, the recursive case is always connecting the first item and the function(rest of the list)
-
Towers of Hanoi:
-
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks.
-
The objective of the puzzle is to move the entire stack to another rod
-
Only one disk can be moved at a time.
-
Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
-
No disk may be placed on top of a smaller disk.
-
-
-
Fibonacci Tower:
-
Pascal’s triangle:
Lecture 21: OOP
- Concepts:
- Inheritance: The transfer of the characteristics of a class to other classes that are derived from it.
- Polymorphism
- Abstraction: shows only important attributes while hiding unnecessary details from the user. It helps in reducing programming complexity and increase efficiency.
- The abstraction is done during the design level of a system and encapsulation is done when the system has been implemented
- Encapsulation: a programming technique that binds the class members together and prevents them from being accessed by other classes. Restricted access to Class members: variables and methods To keep variables and methods safes from outside interference and misuse.
- Object is an instance of a class, with different attributes and methods from one another
- Instance: An individual object of a certain class.
- Class: A user-defined prototype for an object that defines a set of attributes that characterise any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.
- Variables:
- Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class’s methods. Class variables are not used as frequently as instance variables are.
- Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class.
- Data member
- Function overloading: The assignment of more than one behaviour to a particular function. The operation performed varies by the types of objects or arguments involved.
- Operator overloading: The assignment of more than one function to a particular operator.
- When inside a class: method, outside of the class: function
Lecture 22: Design classes and constructors
-
Constructions:
-
Constructor is called whenever new object is initialized
-
Default constructor: no argument to be passed
-
Parameterised constructor: requires multiple parameters with self
-
-
Constructors are automatically created by Python only default constructor
-
An object cannot be created if the class doesn’t have a constructor
-
-
Instantiation:
- New object created is different from another object even though created from the same class
-
Deleting an object:
-
Convert an object to a string when called
- if not, pointer to the object is a memory address
-
Built-in class functions:
- Built-in class attributes:
- Invariants
Lecture 23: Subclasses and inheritance
-
Inheritance:
-
Simple inheritance: a process by which one child class (subclass) takes on the attributes and methods of another, parent (base/super) class
-
newly formed classes that can override or extend the attributes and methods of parent classes
-
-
Multiple inheritance: a class is derived from more than one base class
- The properties and methods of all the base classes are inherited into the derived class.
- First come first serve, so if the name of methods/attributes are repeated then the first parent’s is used
-
Deadly diamond of death (hybrid):
- Class B and C inherits from class A, but class D inherits from both B and C
-
Method resolution order:
-
Check relationship:
-
Lecture 24: Operator and function overloading
-
Operator overloading:
-
Change how objects behave under operations like +, -, *, /, comparision,…
-
-
Function overloading
-
-
(args) passes variable number of non-keyworded arguments as a list
```python def sum_all (*prices): total = 0 for i in prices: total += i print( "Total is ", total) sum_all (100, 200) sum_all (100, 200, 300) ```
-
-
** (kwargs) passes variable number of keyword arguments dictionary to function on which operation of a dictionary can be performed
-
*args and **kwargs make the function flexible.
-
-
Encapsulation: Restrict access to methods and variables to prevent data modification
- Private attributes are prefixed with __
-
Polymorphism:
- Methods in child class has the same name as the methods in the parent class
- Child class modifies the method it has inherited from the parent class
Lecture 25:
- Numpy
- Panda
- Matlib
Week 15 not in final exam