# CP Python: Seance 5 ## 1. Théorie ![](https://i.imgur.com/JHidgdz.png) ### Recherche dichotomique | Linear Search | Binary Search | | -------- | -------- | | `linear_search('mango',lst)` <img src="https://i.imgur.com/oIDFFRs.png" width="1600"> | <img src="https://i.imgur.com/JSAwDdo.png" width="800"> <img src="https://i.imgur.com/uQtV7x5.png" width="900"> | $\Delta$`t_execution` proportionnel à $n$ => $O(n)$ |$\Delta$`t_execution`proportionnel à $log_2(n)$ => $O(log (n))$ | | - [Video 1](https://www.youtube.com/watch?v=DnvWAd-RGhk) - [Video 2](https://www.youtube.com/watch?v=t914IvpnTWQ) ### Fichiers * Pourquoi `close` est nécessaire ? ```python= file = open ( name, "r" ) for line in file: print(line) file.close () ``` * Comment fermer le fichier implicitement ? ```python with open ( name, "w" ) as file: # opérations sur fichier file ... ``` * `strip()`, `split()`, `int()`, `tuple()`, `float()` <div style="text-align:center"> <img src="https://i.imgur.com/Ixpiwnh.png" width=500> </div> ### Exceptions * A quoi ça sert d'intercepter une Erreur (Exception) ? ```python= num = input ( "Provide a number: " ) try: # Si num == 0, alors Python ordonne d'utiliser raise ValueError print ( 1 / int(num) ) except: print ( "Error doing calculation" ) operation_importante() ``` ```python= def is_number ( text, n ): try: value = int(text) return value >= 0 and value <= n except ValueError: return False ``` * A quoi ça sert de lancer une Erreur (Exception) ? ```python= def askAge (): age = int(input( "Provide your age: " )) if age < 0 or age >= 150: raise ValueError ( "Age out of range" ) return age ``` * Fichiers & Exceptions ```python try: with open ( name, "w" ) as file: # opérations sur fichier file except: # faire qqch en cas d'erreur ``` * Erreur spécifique ? https://docs.python.org/3/library/exceptions.html * exception `ValueError` * exception `DivisionByZero` * exception `IndexError` * lst[i] mais la longueur de lst est plus petite que i p.ex. * exception `FileNotFound` * exception `OSError` ## 2. Exercices 1. __Binary Search__: * Résoudre la question 3 et 4 de la Session 5, disponible ici: https://syllabus-interactif.info.ucl.ac.be/syllabus/info1-exercises/PART_II/MISSION_5/preparation --- 2. __Interrogation__: * Recopier votre code lié à l'interrogation dans un fichier `interro_student.py`. Si vous avez plusieurs solutions, mettez les toutes. * Résoudre une variante de `trouver_doublon` * Ecrire une fonction `trouver_plus_long_PIN` qui permet de retrouver la personne dont le mot de passe est le plus sécurisé, parmi des mots de passe exclusivement numériques, autrement dit le plus long. * Autrement dit, si la liste `pin_list = [('Kim','Mens',1232445),('Olivier','Pecheur',8349),('Aragorn','Premier Du Nom',101)]` est donnée en argument, `trouver_plus_long_PIN(pin_list)` devra retourner le string `"Kim Mens"` * Contrainte: Veuillez ré-utiliser la fonction `count_digits` :wink: --- 3. [Session 6: Q* Hogwarts - Quidditch](https://syllabus-interactif.info.ucl.ac.be/syllabus/info1-exercises/PART_II/MISSION_6/complement) - The scores list would be provided as a file. The content of this file would follow this format: - Two first lines: Names of the team - Lines after: Team_scoring points - In case of error, just raise it. - Remember that the catch of the golden snitch (150 points) means the end of the match. - Implement the function `referee(score_file)` in Python. --- 4. [Session 6 : Q* Sauvegarde](https://syllabus-interactif.info.ucl.ac.be/syllabus/info1-exercises/PART_II/MISSION_6/complement) * You have to create two function, one to save the data and one to load the data previously saved. * You are free to store the data like you want in the file, but putting one integer per line is probably the easiest. * If there is no file to load when using the function `load_data` (for exemple, the player starts a new game), you must raise a FileNotFoundError. * The two functions will have these definition : ```python= #save the 4 integer to the file named filename def save_data(filename, life, mana, position_x, position_y): #return a tuple containing (life, mana, position_x, position_y) previously saved def load_data(filename): ``` --- ### Resources de la séance passée: * Le document principal https://hackmd.io/@Tb5Z2PdeRLSnkxJEsjcLXg/rk5z1u_5v * Le repl: https://repl.it/@GuillaumeGst/CP-Python-Seance-4-1