PYTHON NOTES MAIN CHARACTERISTICS Case sensitive Indentation sensitive Garbage collector Dynamically type: data of all types can be stored into the same variable Inferred type: identifies the type of data VARIABLES Naming rules: No spaces Start with “_” or a letter Lower camel case (myVariable) Delete: del a a = None Data types: Int Bool Float Str Complex OPERATORS ARITMETIC +,-,*,/ ** : power % : remainder // : integer division 1 STRING + : concatenate *: repeat len() [0:2] : slicing, takes the first 2 characters [0,2) RELATIONAL ==, >, >=, <, <=, != LOGICAL and, or, not PRECEDENCE 1. () 5. +- 9. is, isnot 2. ** 6. <=,< … 10. in , not in 3. +, - : as signs 7. ==, != 11. and, or , not 4. * / % // 8. = BUILD IN FUNCTIONS type(nameVar): returns the type of variable nameVar isinstance(nameVar, typeVar): returns True if variable nameVar has a type of typeVar abs(x): returns the absolute value of the number x round(x,y): returns number x rounded to a decimal point y pow(x,y): returns number x to the power of y (same as **) range(x,y,step): represents the range [x,y) stepping “step”, can also be range(x) or range(x,y) RANDOM MODULE (IMPORT RANDOM) random.random() chooses a floating number in the range [0,1) random.randrange(x,y) chooses an integer number in the range [a,b) 2 random.randint(x,y) chooses an integer number in the range [a,b] random.uniform(x,y) chooses a floating number in the range [a,b) SIMPLE DATA STRUCTUR ES LISTS [ , , ] METHODS list.append(x): adds item at the end (way better and faster than +) list.insert(x,e): inserts an item e in the position x list.extend(list2[x:y]): adds the elements sliced of list2 to list list.remove(x): removes the first item from list whose value is x list.index(x, start, end): returns the index of the first item in list whose value is x list.count(x): returns the number of occurrences of x in list list.pop(index): removes and returns the item at the index in list; if x not specify removes and returns the last item list.reverse(): reverses the items of list list.sort(): sorts the items of list list.clear(): removes all items from list del list[position]: deletes the element at the selected position OPERATORS: +, *, slicing, in, not in, len(list), del(list), print(list) COPYING list.copy(): makes a deep copy of the list. EX: list2 = list1.copy() COMPARE: == : to know if they are equal is : to know if they are the same 3 NESTED LISTS Lists inside lists. EX: list1 = [[1, 2], 3] DEEP COPY for i in list1: if type(i) is not list: list2.append(i) else: list2.append([]) list2[-1].extend(i) TUPLES ( , , ) tuple.index(x): returns the index of the first element in tuple whose value is x tuple.count(x): returns the number of occurrences of x in tuple +, *, slicing, in, not in, len(tuple), del(tuple), print(tuple) Deep copy: use the assignment operator (=) There are tuples of lists, which can be modified using list operators. EX: tuple1[0].append(2) PACKING- UNPACKING (FOR LISTS AND TUPLES) Packing: list1 = [1,2,3] Unpacking: var1, var2, var3 = list1 ; print(var2) : 2 CASTING SOMETHING ITERABLE TO LIST OR TU PLE list() , tuple() lists, strings, tuples and ranges are iterable DICTIONARIES {‘KEY1’: ELEM1, ‘KEY2’: ELEM2, ‘KEY3’: E LEM3} EXAMPLE: dic = {‘name’: ‘Pepe’, ‘age’: 22} 4 print(dic[‘name’]) Pepe (if the key wasn’t in dic it will raise an error) dic[‘age’] = 14 changes the dictionary dic[‘weight’] = 67 extends the dictionary del dic[‘age’] deletes the key OPERATORS: in, not in, len(dict), del(dict), print(dict) METHODS dict.get(‘key’): returns the value of the specify key dict.values(): returns a list of all the values in the dictionary dict.keys(): returns a list of all the keys in the dictionary dict.items(): returns a list containing a tuple for each key value pair dict.clear(): removes all the elements from the dictionary dict.copy(): returns a copy of the dictionary ‘key’ in dict FUNCTIONS DEFINIG A FUNCTION def function_name(parameters): ‘’’docstring’’’ Instructions return [expression] DEFAULT VALUES def function_defaults(param1: int = 1): SCOPE OF A VARIABLE The part of the program where a variable can be used Global Variables Local Variables: declared inside a function, can only be used in the function 5 RECURSION A function that invokes itself. EXAMPLE: (factorial) def factorial(number): if number == 1 or number == 0: return 1 else: return number * factorial(number – 1) OBJECT ORIENTED PROGRAMMING CLASSES Generic definition for a type of object. DEFINIG A CLASS class MyNewClass: ‘’’docstring’’’ Attributes Methods ACCESING ATTRIBUTES AND METHODS obj1 = MyNewClass() obj1.attribute1 obj1.method1 OBJECTS COPYING: the only way to do it is by hand (‘=’ does not copy, both will become the same object) COMPARING: if we have two different objects with the same attributes ‘obj1 == obj2’ will be ‘False’. 6 METHODS The functions inside a class. They always have the ‘self’ parameter. SPECIAL METHODS __init__(): assigns values to the attributes the moment the object is created. __str__(): returns a string to be printed. Executed when we ‘print’ the object. __repr__(): executed every time we put the name of an object. __eq__(): returns if two objects are equal. Executed when we use obj1 = obj2. INFORMATION HIDING Allows making some attributes private EXAMPLE: self.__atr1 = 3 COMPOSITION Using an object as an attribute of another object. OOP BASIC PRINCIPLES ENCAPSULATION Prevent data from direct modification. PROPERTIES __init__(self, day): self.day = day @property def day(self): return self.__day @day.setter (here we would check the values) def day(self, day): self.__day = day 7 INHERITANCE A process of using details from a new class without modifying an existing class. To access the functions of the first class we use super(). EXAMPLE: class Product: def __init__(self, name, price): self.__name = name self.__price = price def printInfo(self): print(self.__name + ’: ’ + str(self.__price)) class FreshProduct(Product): def __init__(self,name, price, expirationDate): super().__init__(name,price) self.__expirationDate = expirationDate def printInfo(self): print(super().printInfo() + self.__expirationDate.printDate()) ABSTRACT CLASS: a class created only to inherit from it, not to create objects. EX: a RegularPolygon class, used to create the Square class and the Triangle class. POLYMORPHISM A concept of using common operation in different ways for different data input. 8 SORTING AND SEARCHING ALGORITHMS BUBBLE SORT Comparing pair by pair. def bubbleSort(aList: list): # Variable to stop working if the list is already sorted swapping = True # number of iterations of the outer loop num = len(aList) - 1 # outer loop: (elements-1) loops max while num > 0 and swapping: # At the beginning of each iteration we haven't swapped swapping = False # Inner loop (len(list)-number comparisons) for i in range(num): # if the lower index element is bigger than the next one, we swap if aList[i] > aList[i + 1]: # we did a change, so we update the variable swapping = True # we use aux to swap, notice that in Python we don't really need this aux variable as we can do: aList[i], aList[i + 1] = aList[i + 1], aList[i] aux = aList[i] aList[i] = aList[i + 1] aList[i + 1] = aux # One full iteration performed, we decrease the number of pending ones num -= 1 9 INSERTION SORT We insert the element in its place. def insertionSort(aList): # The first element is a sorted sublist, so we start in the second one. At each iteration the index first elements will be already sorted for index in range(1, len(aList)): # we store the value of the first unsorted element currentvalue = aList[index] # now we go backwards looking for its place in the sorted sublist position = index # we iterate while there are elements in the sorted sublist and the value of the element we want to insert into it is higher than the value of the current element (position-element) while position > 0 and aList[position-1] > currentvalue: # we swap elements aList[position] = aList[position-1] # decrementing position to walk through the list backwards position = position-1 # Once found where the element should be placed we place it aList[position] = currentvalue 10 SELECTION SORT Selects the element from smallest to bigger and puts them on its place. def selectionSort(aList:list): # we iteratively search for the lowest element of the list for i in range(len(aList)): # in each iteration the first non-sorted element is the "lowest" (to start comparisons) minPos = i minValue = aList[i] # We use this loop to look for the lowest in the remaining ones for j in range(i + 1, len(aList)): # If the current element is lower than the minValue, its value is now minValue if (aList[j] < minValue): minValue = aList[j] # We mark also its position minPos = j # once the lowest is found, we swap it with the element at position i aList[minPos] = aList[i] aList[i] = minValue LINEAR SEARCH def linearSearch(item, aList: list) -> int: for i in range(len(aList)): if aList[i] == item: return i # If this is executed the item is not in the list return None 11 BINARY SEARCH def binarySearch(item, aList: list) -> int: ''' Function implementing binary search in a list. To use it the list must be sorted. It returns the position of the item in the list or none if the item does not belong to the list. Notice that if the element is repeated it may return the position of any of the repetitions, not always the first one as linear search would do''' first = 0 last = len(aList) – 1 while first <= last: central = (first + last) // 2 # if our element is at central position, we found it if aList[central] == item: return central # if not, if it is lower than central, we discard the upper half of the list elif aList[central] > item: last = central - 1 # if not, it will we higher, so we discard the lower half of the list elif aList[central] < item: first = central + 1 # if not found, return None return None 12