├── 001. Liste des diviseurs d'un nombre entier └── get_dividers.py ├── 002. Tester si un nombre est premier └── is_prime.py ├── 003. Liste des nombres premiers dans un intervalle └── get_primes_list.py ├── 004. Liste des diviseurs qui sont premiers └── list_prime_dividers.py ├── 005. Liste des nombres premiers de Sophie Germain └── get_list_prime_sophie_germain.py ├── 006. Tester si un nombre est une puissance d'un autre nombre └── is_power_another_number.py ├── 007. Tester si un nombre est parfait └── is_perfect.py ├── 008. Liste des nombres parfaits dans un intervalle └── get_perfect_numbers_list.py ├── 009. Recherche du minimum d'une liste └── min_list.py ├── 010. Recherche du maximum d'une liste └── max_list.py ├── 011. L'algorithme de Héron └── heron.py ├── 012. Suite de Fibonacci et mémoïsation ├── fibo_memo.py └── fibonacci.py ├── 013. Echanger 2 valeurs └── switch_value.py ├── 014. Tri à bulles └── tri_a_bulles.py ├── 015. Inverser une chaîne de caractères └── reverse_string.py ├── 016. Somme des éléments d'une liste └── somme.py ├── 017. Moyenne arithmétique des éléments d'une liste └── moyenne_arithmetique.py ├── 018. Moyenne harmonique des éléments d'une liste └── harmonique.py ├── 019. Moyenne quadratique des éléments d'une liste └── moyenne_quadratique.py ├── 020. Moyenne géométrique des éléments d'une liste └── moyenne_geometrique.py ├── 021. Variance et écart-type des éléments d'une liste └── variance.py ├── 022. Calculer le factoriel d'un nombre └── factorial.py ├── 023. Recréer la fonction len() └── length.py ├── 024. Calculer la puissance d'un nombre └── puissance.py ├── 025. Somme des puissances d'un nombre └── somme_puissance.py ├── 026. Développer l'identité remarquable (a+b)² └── identite.py ├── 027. Développer l'identité remarquable (a-b)² └── identite.py ├── 028. Développer l'identité remarquable a² -b² └── identite.py ├── 029. Supprimer les éléments d'une liste └── delete_from_list.py ├── 030. Concaténer deux listes └── concatenate.py ├── 032. Rechercher un élément dans une liste └── find_element.py ├── 033. Résoudre un polynôme du second degré └── polynome.py ├── 034. Nombre d'occurences dans une liste ├── occurrence.py └── test_occurrence.py ├── 035. Recréer la méthode join() ├── pjoin.py └── test_pjoin.py ├── 036. Déterminer si une année est bissextile ├── bissextile.py └── test_bissextile.py ├── 037. Convertir des secondes en heures, minutes, secondes ├── convert_seconds.py └── test_convert_seconds.py ├── 038. Les cycles avec le modulo ├── distribution_carte.py └── jour_de_la_semaine.py ├── 039. Obtenir les valeurs dans la table ascii ├── ascii.py └── code_ascii_accent.py ├── 040. Le chiffre de César ├── cesar.py └── test_cesar.py ├── 041. Résoudre une équation du premier degré ├── solve_equation.py └── test_solve_equation.py ├── 042. Tester si une chaîne de caractères ne contient que des nombres ├── fonctionnement_isnumeric.py ├── is_numeric.py └── test_is_numeric.py ├── 043. Tester si tous les mots d'une chaîne de caractères commencent par une majuscule ├── fonctionnement_istitle.py ├── is_title.py └── test_is_title.py ├── 044. Renvoyer une chaîne de caractères entièrement en minuscule ou majuscule ├── code_ascii_accent.py ├── lower_upper.py ├── plower_pupper.py └── test_plower_pupper.py ├── 045. Enlever les doublons dans une liste ├── no_order_doublon.py ├── order_doublon.py └── test_order_doublon.py ├── 046. Tester si une chaîne de caractères contient uniquement des lettres de l'alphabet ├── only_alphabet.py ├── python_isalpha.py └── test_only_alphabet.py ├── 047. Somme de tous les éléments d'un dictionnaire ├── sum_dict.py └── test_sum_dict.py ├── 048. Fusionner deux dictionnaires ├── __pycache__ │ └── merge_dict.cpython-38.pyc ├── merge_dict.py └── test_merge_dict.py ├── 049. Multiplier toutes les valeurs d'un dictionnaire ├── multi_dict.py └── test_multi_dict.py ├── 050. Trouver la valeur maximale d'un dictionnaire ├── max_dict.py └── test_max_dict.py ├── 051. Trouver la valeur minimale d'un dictionnaire ├── min_dict.py └── test_min_dict.py ├── 052. Transformer deux listes en un dictionnaire ├── test_two_lists_to_dict.py └── two_lists_to_dict.py ├── 053. Supprimer tous les éléments d'une liste ├── clear.py ├── pclear.py └── test_pclear.py ├── 054. Afficher les éléments d'un dictionnaire triés par clé ├── sort_dict.py └── test_sort_dict.py ├── 055. Supprimer le caractère à l'indice n d'une chaîne de caractères ├── delete_char.py └── test_delete_char.py ├── 056. Liste - Différence entre remove, pop et del └── difference_entre_pop_remove_del.py ├── 057. Tester si une date est valide ├── date_is_valid.py └── test_date_is_valid.py ├── 058. Inverser un nombre entier ├── inverser_entier.py └── test_inverser_entier.py ├── 059. Convertir un nombre décimal en binaire ├── decimal_to_binary.py └── test_decimal_to_binary.py ├── 060. Convertir un nombre binaire en décimal ├── binary_to_decimal.py └── test_binary_to_decimal.py ├── 061. Convertir un nombre décimal en hexadécimal ├── decimal_to_hexadecimal.py └── test_decimal_to_hexadecimal.py ├── 062. Convertir un nombre hexadécimal en nombre décimal ├── hexadecimal_to_decimal.py └── test_hexadecimal_to_decimal.py ├── 063. Addition de 2 vecteurs └── vector_add.py ├── 064. Générer une matrice aléatoire ├── generer_matrice_aleatoire.py └── test_generer_matrice_aleatoire.py ├── 065. Calculer l'aire et le périmètre d'un cercle ├── circle.py └── test_circle.py ├── 066. Calculer l'aire et le périmètre d'un triangle ├── test_triangle.py └── triangle.py ├── 067. Calculer l'aire et le périmètre d'un carré ├── carre.py └── test_carre.py ├── 068. Calculer l'aire et le périmètre d'un rectangle ├── rectangle.py └── test_rectangle.py ├── 069. Vérifier que tous les éléments d'une liste sont différents ├── liste_difference.py └── test_liste_difference.py ├── 070. Mélanger les caractères d'une chaîne de caractères ├── shuffle.py └── test_shuffle.py ├── 071. Changer les lettres avec accent en lettres sans accent ├── no_accent.py └── test_no_accent.py ├── 072. Tester si deux mots sont des anagrammes └── anagramme.py ├── 073. Retirer les ponctuations d'une chaîne de caractères ├── retirer_ponctuation.py └── test_retirer_ponctuation.py ├── 074. Tester si une chaîne de caractères est un pangramme ├── no_accent.py ├── pangramme.py ├── retirer_ponctuation.py └── test_pangramme.py ├── 075. Afficher les éléments d'une liste absents d'une autre liste ├── are_in_other_list.py └── test_are_in_other_list.py ├── 076. Calculer la distance entre deux points ├── distance_between_2_points.py └── test_distance_between_2_points.py ├── 077. Calculer l'hypoténuse d'un triangle rectangle ├── hypotenuse.py └── test_hypotenuse.py ├── 078. Tester si toutes les valeurs d'un dictionnaire sont égales ├── same_values.py └── test_same_values.py ├── 079. Tester si une phrase est un heterogramme ├── est_un_heterogramme.py └── test_est_un_heterogramme.py ├── 080. Tester si une phrase est un isogramme ├── est_un_isogramme.py └── test_est_un_isogramme.py ├── 081. Suite de Conway (Count and say) ├── countAndSay.py └── test_countAndSay.py ├── 082. Trier 3 nombres sans utiliser de boucle ni de structure conditionnelle ├── sort_3_numbers.py └── test_sort_3_numbers.py ├── 083. Déterminer l'équation ax+b à partir de 2 points ├── find_equation_line.py └── test_find_equation_line.py ├── 084. Tester si une chaîne de caractères est un palindrome ├── string_is_palindrome.py └── test_string_is_palindrome.py ├── 085. Tester si une phrase est un palindrome ├── is_palindrome.py ├── no_accent.py ├── palindrome_recursion.py └── retirer_ponctuation.py ├── 086. Somme des colonnes et des lignes d'une matrice ├── sum_matrix.py └── test_sum_matrix.py ├── 087. Trouver les sunny numbers dans un intervalle ├── sunny.py └── test_sunny.py ├── 088. Calculer la valeur du nombre d'Euler e ├── euler.py └── test_euler.py ├── 089. Trouver les nombres heureux dans un intervalle ├── happy_numbers.py └── test_happy_numbers.py ├── 090. Trouver les spy numbers dans un intervalle ├── spy_numbers.py └── test_spy_numbers.py ├── 091. Taux de croissance ├── croissance.py └── test_croissance.py ├── 092. Série des nombres triangulaires ├── test_triangulaire.py └── triangulaire.py ├── 093. Calculer la distance Euclidienne ├── euclidean.py └── test_euclidean.py ├── 094. Déterminer si un nombre est pair ou impair └── pair.py ├── 095. Faire la somme de nombres binaires ├── somme_binaire.py └── test_somme_binaire.py ├── 096. Rendu de monnaie ├── __pycache__ │ └── monnaie.cpython-39.pyc ├── monnaie.py └── test_monnaie.py ├── 097. Réinitialiser un objet Python sans le détruire ├── reset.py └── test_reset.py ├── 098. Les nombres strobogrammatiques ├── Définition.txt ├── est_strobogrammatique.py └── test_est_strobogrammatique.py ├── 099. Evil numbers ├── evil.py └── test_evil.py ├── 100. Disarium numbers ├── Définition.txt ├── disarium.py └── test_disarium.py ├── 101. Trimorphic numbers ├── Définition.txt ├── test_trimorphic.py └── trimorphic.py ├── 102. Ugly Number ├── test_ugly.py └── ugly.py ├── 103. Instancier une matrice remplie de zéros ├── matrice_nulle.py └── test_matrice_nulle.py ├── 104. Convertir des nombres entiers en chiffres romains ├── entier_vers_romain.py └── test_entier_vers_romain.py ├── 105. Convertir des chiffres romains en nombres entiers ├── romain_vers_entier.py └── test_romain_vers_entier.py ├── 106. Poids de Hamming ├── poids_hamming.py └── test_poids_hamming.py ├── 107. Distance de Hamming ├── distance_hamming.py └── test_distance_hamming.py ├── 108. Jeu de Nim └── gagneNim.py ├── 109. Strong Number ├── factorial.py ├── strong_number.py └── test_strong_number.py ├── 110. Armstrong Number ├── armstrong.py └── test_armstrong.py ├── 111. Super digit ├── super_digit.py └── test_super_digit.py ├── 112. Triangle de Floyd ├── test_triangle_floyd.py └── triangle_floyd.py ├── 113. Fascinating number ├── fascinating.py └── test_fascinating.py ├── 114. Nombre automorphe ├── 114. Vignette Nombre automorphe.jpg └── test_automorphe.py ├── 115. Tester si une grille de sudoku est valide ├── sudoku_est_valide.py └── test_sudoku_est_valide.py ├── 116. Résoudre une grille de Sudoku └── sudoku.py ├── 117. Afficher le triangle de Pascal ├── test_triangle_pascal.py └── triangle_pascal.py ├── 118. Retourner les éléments présents dans deux listes ├── both_list.py └── test_both_list.py ├── 119. Somme de deux fractions ├── fraction.py └── test_fraction.py ├── 120. Les nombres de Tribonacci ├── test_tribonacci.py └── tribonacci.py ├── 121. Inverser tous les mots d'une chaîne de caractères └── inverse.py ├── 122. Number complement ├── complement.py └── test_complement.py ├── 123. Coefficient binomial ├── binomial.py └── test_binomial.py ├── 124. Ajouter des zéros au début d'un nombre ├── fill.py └── test_fill.py ├── 125. Trouver le PGCD ├── pgcd.py └── test_pgcd.py ├── 126. Initialiser une matrice identité ├── identity.py └── test_identity.py ├── 127. Convertir une chaîne de caractères en Morse ├── morse.py └── test_morse.py ├── 128. Additionner deux nombres complexes ├── complexe.py ├── complexe_2.py ├── test_complexe.py └── test_complexe_2.py ├── 129. Multiplier deux nombres complexes ├── complexe.py ├── complexe_2.py ├── test_complexe.py └── test_complexe_2.py ├── 130. Négation d'un nombre complexe ├── complexe.py ├── complexe_2.py ├── test_complexe.py └── test_complexe2.py ├── 131. Inverse d'un nombre complexe ├── complexe.py ├── complexe_2.py ├── test_complexe.py └── test_complexe_2.py ├── 132. Le conjugué d'un nombre complexe ├── complexe.py ├── complexe_2.py ├── test_complexe.py └── test_complexe_2.py ├── 133. Le module d'un nombre complexe ├── complexe.py ├── complexe_2.py ├── test_complexe.py └── test_complexe_2.py ├── 134. Argument d'un nombre complexe ├── complexe.py ├── complexe_2.py ├── test_complexe.py └── test_complexe_2.py ├── 135. Trouver l'expression du nombre imaginaire i^n ├── expression_i.py └── test_expression_i.py ├── 136. Récupérer un nombre complexe depuis une chaîne de caractères ├── complexe_parser.py └── test_complexe_parser.py ├── 137. Additionner deux matrices ├── add_matrix.py └── test_add_matrix.py ├── 138. Calculer la transposée d'une matrice ├── test_transpose.py └── transpose.py ├── 139. Produit d'Hadamard de deux matrices ├── hadamard.py └── test_hadamard.py ├── 140. Produit scalaire de deux matrices ├── produit_scalaire.py └── test_produit_scalaire.py ├── 141. Produit cartésien de deux ensembles ├── produit_cartesien.py └── test_produit_cartesien.py ├── 142. Multiplier une matrice par un scalaire ├── scalaire_matrice.py └── test_scalaire_matrice.py ├── 143. Produit Kronecker de deux matrices ├── produit_kronecker.py └── test_produit_kronecker.py ├── 144. Calculer le déterminant d'une matrice carrée d'ordre 2 ├── determinant_2.py └── test_determinant_2.py ├── 145. Calculer le déterminant d'une matrice carrée d'ordre 3 ├── determinant_3.py └── test_determinant_3.py ├── 146. Calculer la trace d'une matrice ├── test_trace.py └── trace_matrice.py ├── 147. Calculer le permanent d'une matrice carrée d'ordre 2 ├── permanent_2.py └── test_permanent_2.py ├── 148. Calculer le permanent d'une matrice carrée d'ordre 3 ├── permanent_3.py └── test_permanent_3.py ├── 149. Matrice de Toeplitz ├── test_toeplitz.py └── toeplitz.py ├── 150. Aplatir des listes imbriquées ├── flatten.py └── test_flatten.py ├── 151. Les piles ├── pile.py └── test_pile.py ├── 152. Les files ├── queue.py └── test_file.py ├── 153. Les listes chaînées ├── linkedlist.py ├── node.py └── test_linkedlist.py ├── 154. Inverser une liste chaînée ├── linkedlist.py ├── node.py └── test_inverse_linkedlist.py ├── 155. Les listes chaînées doubles ├── doublylinkedlist.py ├── node.py └── test_doublylinkedlist.py ├── 156. Inverser une liste doublement chaînée ├── inverse_doublylinkedlist.py ├── node.py └── test_inverse_doublylinkedlist.py ├── 157. Renvoyer le noeud au milieu d'une liste chaînée ├── linkedlist.py ├── node.py └── test_linkedlist.py ├── 158. Echanger les nœuds d'une liste chaînée par pair ├── linkedlist.py ├── node.py └── test_linkedlist.py ├── 159. Déterminer si une liste chaînée est cyclique ├── linkedlist.py └── node.py ├── 160. Donner le noeud où commence le cycle d'une liste chaînée cyclique ├── linkedlist.py └── node.py ├── 161. Partitionner une liste chaînée ├── linkedlist.py ├── node.py └── test_partition.py ├── 162. Déterminer si une liste chaînée simple est palindromique ├── linkedlist.py ├── node.py └── test_is_palindrome.py ├── 163. Déterminer si une liste doublement chaînée est palindromique ├── doublylinkedlist.py ├── node.py └── test_palindrome_doublylinkedlist.py ├── 164. Additionner deux nombres formés par une liste chaînée ├── addition_number_linkedlist.py ├── linkedlist.py ├── node.py └── test_addition_number_linked_list.py ├── 165. Convertir un nombre binaire contenue dans une liste chaînée en un nombre entier ├── convert_binary_linkedlist.py ├── linkedlist.py ├── node.py └── test_convert_binary_linkedlist.py ├── Exercices d'algorithmie.ods └── README.md /001. Liste des diviseurs d'un nombre entier/get_dividers.py: -------------------------------------------------------------------------------- 1 | def get_dividers(n): 2 | """Renvoie la liste des diviseurs du nombre entier n envoyé en paramètre""" 3 | dividers_list = [] 4 | for divider in range(1, n+1): 5 | if n % divider == 0: 6 | dividers_list.append(divider) 7 | 8 | return dividers_list 9 | -------------------------------------------------------------------------------- /002. Tester si un nombre est premier/is_prime.py: -------------------------------------------------------------------------------- 1 | def is_prime(n): 2 | """Renvoie un booléen indiquant si le nombre n est un nombre premier (True) 3 | ou non (False)""" 4 | for d in range(2,n): 5 | if n % d == 0: 6 | return False 7 | return True 8 | -------------------------------------------------------------------------------- /003. Liste des nombres premiers dans un intervalle/get_primes_list.py: -------------------------------------------------------------------------------- 1 | def is_prime(n): 2 | """Renvoie un booléen indiquant si le nombre n est un nombre premier (True) 3 | ou non (False)""" 4 | for d in range(2,n): 5 | if n % d == 0: 6 | return False 7 | return True 8 | 9 | def get_primes_list(inf, sup): 10 | """Renvoie la liste des nombres premiers compris dans l'intervalle [inf, sup]""" 11 | primes_list = [] 12 | for num in range(inf, sup+1): 13 | if is_prime(num): 14 | primes_list.append(num) 15 | return primes_list 16 | -------------------------------------------------------------------------------- /004. Liste des diviseurs qui sont premiers/list_prime_dividers.py: -------------------------------------------------------------------------------- 1 | def is_prime(nb): 2 | """Teste si nb est un nombre premier. Renvoie True si il est premier 3 | ou False sinon""" 4 | if nb < 2: 5 | return False 6 | for d in range(2,nb): 7 | if nb % d == 0: 8 | return False 9 | return True 10 | 11 | def get_dividers(nb): 12 | """Retourne la liste des diviseurs du nombre nb""" 13 | dividers_list = [] 14 | for divider in range(1, nb+1): 15 | if nb % divider == 0: 16 | dividers_list.append(divider) 17 | 18 | return dividers_list 19 | 20 | def get_prime_dividers(nb): 21 | """Retourne la liste des diviseurs du nombre nb qui sont premiers""" 22 | dividers_prime_list = [] 23 | for divider in get_dividers(nb): 24 | if is_prime(divider): 25 | dividers_prime_list.append(divider) 26 | 27 | return dividers_prime_list 28 | -------------------------------------------------------------------------------- /005. Liste des nombres premiers de Sophie Germain/get_list_prime_sophie_germain.py: -------------------------------------------------------------------------------- 1 | def is_prime(n): 2 | """Teste si un nombre est premier. Renvoie True si il l'est, False sinon""" 3 | for d in range(2,n): 4 | if n % d == 0: 5 | return False 6 | return True 7 | 8 | def is_prime_sophie_germain(n): 9 | """Teste si un nombre est un nombre premier de Sophie Germain""" 10 | if is_prime(n) and is_prime(2*n + 1): 11 | return True 12 | else: 13 | return False 14 | 15 | def get_list_primes_sophie_germain(inf, sup): 16 | """Renvoie la liste des nombres premiers de Sophie Germain présents dans 17 | un intervalle [inf, sup]""" 18 | list_primes_sophie_germain = [] 19 | for num in range(inf, sup+1): 20 | if is_prime_sophie_germain(num): 21 | list_primes_sophie_germain.append(num) 22 | 23 | return list_primes_sophie_germain 24 | 25 | print(is_prime_sophie_germain(2)) 26 | print(is_prime_sophie_germain(3)) 27 | print(is_prime_sophie_germain(5)) 28 | print(is_prime_sophie_germain(12)) 29 | print(is_prime_sophie_germain(4055)) 30 | 31 | print(get_list_primes_sophie_germain(1, 100)) 32 | print(get_list_primes_sophie_germain(1, 500)) 33 | print(get_list_primes_sophie_germain(1, 1000)) 34 | -------------------------------------------------------------------------------- /006. Tester si un nombre est une puissance d'un autre nombre/is_power_another_number.py: -------------------------------------------------------------------------------- 1 | def is_power_another_number(n,p): 2 | """Teste si un nombre n est la puissance d'un autre nombre i à la puissance p""" 3 | for i in range(1, n): 4 | if i**p > n: 5 | return False 6 | elif i**p == n: 7 | return True 8 | 9 | 10 | print(is_power_another_number(100,2)) 11 | print(is_power_another_number(27,3)) 12 | print(is_power_another_number(100,3)) 13 | print(is_power_another_number(81,3)) 14 | print(is_power_another_number(243,3)) 15 | print(is_power_another_number(25,2)) 16 | -------------------------------------------------------------------------------- /007. Tester si un nombre est parfait/is_perfect.py: -------------------------------------------------------------------------------- 1 | #Un nombre parfait est égal à la somme de ses diviseurs stricts 2 | 3 | def get_dividers(nb): 4 | """Renvoie la liste des diviseurs du nombre nb""" 5 | dividers_list = [] 6 | for divider in range(1, nb+1): 7 | if nb % divider == 0: 8 | dividers_list.append(divider) 9 | 10 | return dividers_list 11 | 12 | def is_perfect(nb): 13 | """Teste si un nombre est parfait (True) ou non (False).""" 14 | print(get_dividers(28)) 15 | if sum(get_dividers(nb)[:-1]) == nb: 16 | return True 17 | else: 18 | return False 19 | 20 | print(is_perfect(28)) 21 | -------------------------------------------------------------------------------- /008. Liste des nombres parfaits dans un intervalle/get_perfect_numbers_list.py: -------------------------------------------------------------------------------- 1 | def get_dividers(nb): 2 | """Renvoie la liste des diviseurs du nombre nb""" 3 | dividers_list = [] 4 | for divider in range(1, nb+1): 5 | if nb % divider == 0: 6 | dividers_list.append(divider) 7 | 8 | return dividers_list 9 | 10 | def is_perfect(nb): 11 | """Renvoie True si nb est un nombre parfait, False sinon.""" 12 | if sum(get_dividers(nb)[:-1]) == nb: 13 | return True 14 | else: 15 | return False 16 | 17 | 18 | def get_perfect_numbers_list(inf, sup): 19 | """Renvoie la liste des nombres parfaits dans l'intervalle [inf,sup]""" 20 | perfect_numbers_list = [] 21 | for n in range(inf, sup+1): 22 | if is_perfect(n): 23 | perfect_numbers_list.append(n) 24 | return perfect_numbers_list 25 | 26 | print(get_perfect_numbers_list(1, 1000)) 27 | -------------------------------------------------------------------------------- /009. Recherche du minimum d'une liste/min_list.py: -------------------------------------------------------------------------------- 1 | def min_list(liste): 2 | """Renvoie la valeur minimale d'une liste""" 3 | minimum = liste[0] 4 | for i in range(1, len(liste)): 5 | if minimum > liste[i]: 6 | minimum = liste[i] 7 | return minimum 8 | 9 | def recursion_min_list(liste, i=0, min_liste=0): 10 | """Renvoie la valeur minimale d'une liste""" 11 | if i < len(liste): 12 | if i == 0 or liste[i] < min_liste: 13 | min_liste = liste[i] 14 | min_liste = recursion_min_list(liste, i+1, min_liste) 15 | return min_liste 16 | 17 | -------------------------------------------------------------------------------- /010. Recherche du maximum d'une liste/max_list.py: -------------------------------------------------------------------------------- 1 | def max_list(liste): 2 | """Renvoie la valeur maximale d'une liste""" 3 | maximum = liste[0] 4 | for i in range(1, len(liste)): 5 | if maximum < liste[i]: 6 | maximum = liste[i] 7 | return maximum 8 | 9 | def recursion_max_list(liste, i=0, max_liste=0): 10 | """Renvoie la valeur maximale d'une liste""" 11 | if i < len(liste): 12 | if i == 0 or liste[i] > max_liste: 13 | max_liste = liste[i] 14 | max_liste = recursion_max_list(liste, i+1, max_liste) 15 | return max_liste 16 | -------------------------------------------------------------------------------- /011. L'algorithme de Héron/heron.py: -------------------------------------------------------------------------------- 1 | from math import * 2 | 3 | #Détermine les valeurs approchées de racine de n, pour l'entier naturel n 4 | #u1 = n 5 | #u2 = 0.5*(u1 + n/u1) 6 | #u3 = 0.5*(u2 + n/u2) 7 | 8 | def heron(n,p): 9 | u = n 10 | while(u - sqrt(n) > p): 11 | u = 0.5*(u + n/u) 12 | 13 | return u 14 | -------------------------------------------------------------------------------- /012. Suite de Fibonacci et mémoïsation/fibo_memo.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | """Renvoie le n-ème terme de la suite de Fibonacci en utilisant la mémoïsation""" 3 | global values 4 | 5 | if not n in values.keys(): 6 | values[n] = fibonacci(n-1)+ fibonacci(n-2) 7 | return values[n] 8 | 9 | 10 | values = {1 : 1, 2 : 1} 11 | -------------------------------------------------------------------------------- /012. Suite de Fibonacci et mémoïsation/fibonacci.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | """Renvoie le n-ème terme de la suite de Fibonacci""" 3 | if n==1 or n==2: 4 | return 1 5 | else: 6 | return fibonacci(n-1) + fibonacci(n-2) 7 | -------------------------------------------------------------------------------- /013. Echanger 2 valeurs/switch_value.py: -------------------------------------------------------------------------------- 1 | def switch_value_temp(a,b): 2 | """Echange les valeurs de 2 variables en utilisant une variable temporaire""" 3 | temp = a 4 | a = b 5 | b = temp 6 | return a, b 7 | 8 | def switch_value_addition(a,b): 9 | """Echange les valeurs de 2 variables grâce à l'arithmétique""" 10 | a = a + b 11 | b = a - b 12 | a = a - b 13 | return a, b 14 | 15 | def switch_value_python(a,b): 16 | """Echange les valeurs de 2 variables de manière pythonesque""" 17 | a, b = b, a 18 | return a, b 19 | -------------------------------------------------------------------------------- /014. Tri à bulles/tri_a_bulles.py: -------------------------------------------------------------------------------- 1 | def bubble_sort(liste): 2 | """Trie une liste en utilisant l'algorithme du tri à bulles""" 3 | 4 | permutation = True 5 | j = 0 6 | while permutation: 7 | permutation = False 8 | j = j + 1 9 | for i in range(0, len(liste) - j): 10 | if liste[i] > liste[i+1]: 11 | liste[i], liste[i+1] = liste[i+1], liste[i] 12 | permutation = True 13 | 14 | return liste 15 | 16 | liste = [9,8,7,6,5,4,3,2,1] 17 | print(bubble_sort(liste)) 18 | -------------------------------------------------------------------------------- /015. Inverser une chaîne de caractères/reverse_string.py: -------------------------------------------------------------------------------- 1 | def reverse_recurrence(string): 2 | """Inverse une chaîne de caractères par récurrence""" 3 | new_string = "" 4 | if string != "": 5 | new_string = reverse_recurrence(string[1:]) + string[0] 6 | return new_string 7 | 8 | 9 | 10 | def reverse_loop(string): 11 | """Inverse une chaîne de caractères en utilisant une boucle""" 12 | new_string = "" 13 | for letter in string: 14 | new_string = letter + new_string 15 | return new_string 16 | 17 | 18 | 19 | def reverse_join(string): 20 | """Inverse une chaîne de caractères grâce à la méthode join()""" 21 | string = "".join(reversed(string)) 22 | return string 23 | 24 | 25 | 26 | def reverse_python(string): 27 | """Inverse une chaîne de caractères de manière pythonesque""" 28 | return string[::-1] 29 | -------------------------------------------------------------------------------- /016. Somme des éléments d'une liste/somme.py: -------------------------------------------------------------------------------- 1 | def somme(liste): 2 | """Calcul la somme des éléments d'une liste""" 3 | total = 0 4 | for nombre in liste: 5 | total += nombre 6 | return total 7 | 8 | def somme_recursion(liste, indice=0): 9 | """Calcul la somme des éléments d'une liste par récursion""" 10 | total = 0 11 | if indice < len(liste): 12 | total = liste[indice] 13 | total += somme_recursion(liste, indice+1) 14 | 15 | return total 16 | -------------------------------------------------------------------------------- /017. Moyenne arithmétique des éléments d'une liste/moyenne_arithmetique.py: -------------------------------------------------------------------------------- 1 | def moyenne_arithmetique(liste): 2 | """Calcul la moyenne arithmétique des éléments d'une liste""" 3 | return (1/len(liste)) * sum(liste) 4 | -------------------------------------------------------------------------------- /018. Moyenne harmonique des éléments d'une liste/harmonique.py: -------------------------------------------------------------------------------- 1 | #Moyenne harmonique : N / sum(1/ai) 2 | 3 | def harmonique(liste): 4 | """Renvoie la moyenne harmonique des éléments d'une liste""" 5 | sum_liste = 0 6 | for nb in liste: 7 | sum_liste += (1/nb) 8 | 9 | return len(liste) / sum_liste 10 | -------------------------------------------------------------------------------- /019. Moyenne quadratique des éléments d'une liste/moyenne_quadratique.py: -------------------------------------------------------------------------------- 1 | from math import * 2 | 3 | def quadratique(liste): 4 | """Renvoie la moyenne quadratique des éléments d'une liste""" 5 | sum_liste = 0 6 | for nb in liste: 7 | sum_liste += nb**2 8 | return sqrt(sum_liste/len(liste)) 9 | 10 | -------------------------------------------------------------------------------- /020. Moyenne géométrique des éléments d'une liste/moyenne_geometrique.py: -------------------------------------------------------------------------------- 1 | def geometrique(liste): 2 | """Renvoie la moyenne géométrique des éléments d'une liste""" 3 | product_list = 1 4 | for nb in liste: 5 | product_list *= nb 6 | 7 | return product_list**(1/len(liste)) 8 | -------------------------------------------------------------------------------- /021. Variance et écart-type des éléments d'une liste/variance.py: -------------------------------------------------------------------------------- 1 | from math import * 2 | 3 | 4 | 5 | def moyenne(liste): 6 | return (1/len(liste)) * sum(liste) 7 | 8 | 9 | 10 | def variance(liste): 11 | moy = moyenne(liste) 12 | var = 0 13 | 14 | for nb in liste: 15 | var += (nb - moy)**2 16 | 17 | return var / len(liste) 18 | 19 | 20 | 21 | def ecart_type(liste): 22 | moy = moyenne(liste) 23 | var = 0 24 | for nb in liste: 25 | var += (nb - moy)**2 26 | 27 | return sqrt(var/len(liste)) 28 | -------------------------------------------------------------------------------- /022. Calculer le factoriel d'un nombre/factorial.py: -------------------------------------------------------------------------------- 1 | def factorial(nb): 2 | """Calcul nb!""" 3 | product = 1 4 | for num in range(1, nb+1): 5 | product *= num 6 | 7 | return product 8 | 9 | def recursion_factorial(nb): 10 | """Calcul nb! avec une récursion""" 11 | if nb==1: 12 | return 1 13 | return nb*recursion_factorial(nb-1) 14 | -------------------------------------------------------------------------------- /023. Recréer la fonction len()/length.py: -------------------------------------------------------------------------------- 1 | def length(liste): 2 | """Renvoie le nombre d'éléments que contient la liste""" 3 | total = 0 4 | for element in liste: 5 | total += 1 6 | return total 7 | -------------------------------------------------------------------------------- /024. Calculer la puissance d'un nombre/puissance.py: -------------------------------------------------------------------------------- 1 | def puissance(n, p): 2 | """Renvoie n**p""" 3 | if p==0: 4 | return 1 5 | elif p==1: 6 | return n 7 | else: 8 | total=1 9 | for i in range(p): 10 | total *= n 11 | return total 12 | 13 | def recursion_puissance(n, p): 14 | """Renvoie n**p calculé par récursion""" 15 | if p==0: 16 | return 1 17 | elif p==1: 18 | return n 19 | else: 20 | return recursion_puissance(n, p-1)*n 21 | -------------------------------------------------------------------------------- /025. Somme des puissances d'un nombre/somme_puissance.py: -------------------------------------------------------------------------------- 1 | def puissance(n, p): 2 | """Renvoie n**p""" 3 | if p==0: 4 | return 1 5 | elif p==1: 6 | return n 7 | else: 8 | total=1 9 | for i in range(p): 10 | total *= n 11 | return total 12 | 13 | def somme_puissance(nb, k): 14 | total = 0 15 | for i in range(k): 16 | total += puissance(nb, i) 17 | return total 18 | -------------------------------------------------------------------------------- /026. Développer l'identité remarquable (a+b)²/identite.py: -------------------------------------------------------------------------------- 1 | def identite(a, b): 2 | """Développe l'identité remarquable (a+b)²""" 3 | M = a**2 4 | N = 2*a*b 5 | P= b**2 6 | return M,N,P 7 | -------------------------------------------------------------------------------- /027. Développer l'identité remarquable (a-b)²/identite.py: -------------------------------------------------------------------------------- 1 | def identite(a, b): 2 | """Développe l'identité remarquable (a-b)²""" 3 | M = a**2 4 | N = -1*2*a*b 5 | P= b**2 6 | return M,N,P 7 | -------------------------------------------------------------------------------- /028. Développer l'identité remarquable a² -b²/identite.py: -------------------------------------------------------------------------------- 1 | def identite(a,b): 2 | """Factorise l'identité remarquable a² - b²""" 3 | M = a-b 4 | N = a+b 5 | return M,N 6 | -------------------------------------------------------------------------------- /029. Supprimer les éléments d'une liste/delete_from_list.py: -------------------------------------------------------------------------------- 1 | def delete(liste, element_to_delete): 2 | """Supprime un élément d'une liste""" 3 | new_list = list() 4 | 5 | for element in liste: 6 | if not element == element_to_delete: 7 | new_list.append(element) 8 | 9 | return new_list 10 | 11 | def delete_liste(liste, elements_to_delete): 12 | """Supprime plusieurs éléments d'une liste""" 13 | new_list = list() 14 | 15 | for element in liste: 16 | if not element in elements_to_delete: 17 | new_list.append(element) 18 | 19 | return new_list 20 | -------------------------------------------------------------------------------- /030. Concaténer deux listes/concatenate.py: -------------------------------------------------------------------------------- 1 | def concatenate(liste1, liste2): 2 | """Concatène deux listes et renvoie la nouvelle liste créée""" 3 | new_list = list() 4 | 5 | for liste in [liste1, liste2]: 6 | for element in liste: 7 | new_list.append(element) 8 | 9 | return new_list 10 | -------------------------------------------------------------------------------- /032. Rechercher un élément dans une liste/find_element.py: -------------------------------------------------------------------------------- 1 | #Recoder la méthode index() d'une liste 2 | def find_index(liste, to_find): 3 | for i, element in enumerate(liste): 4 | if element == to_find: 5 | return i 6 | return -1 7 | -------------------------------------------------------------------------------- /033. Résoudre un polynôme du second degré/polynome.py: -------------------------------------------------------------------------------- 1 | from math import * 2 | 3 | def discriminant(a,b,c): 4 | """Calcul le discriminant du polynôme du second degré""" 5 | return b**2 - 4*a*c 6 | 7 | def polynome(a,b,c): 8 | """Retourne la solution du polynôme du second degré""" 9 | delta = discriminant(a,b,c) 10 | if delta < 0: 11 | return None, None 12 | elif delta == 0: 13 | return -b / (2*a), None 14 | else: 15 | x1 = (-b+sqrt(delta))/2*a 16 | x2 = (-b-sqrt(delta))/2*a 17 | return x1, x2 18 | -------------------------------------------------------------------------------- /034. Nombre d'occurences dans une liste/occurrence.py: -------------------------------------------------------------------------------- 1 | def occurrence(liste, to_find): 2 | """Compte le nombre d'occurrence d'un élément dans une liste.""" 3 | total = 0 4 | for element in liste: 5 | if element == to_find: 6 | total += 1 7 | return total 8 | -------------------------------------------------------------------------------- /034. Nombre d'occurences dans une liste/test_occurrence.py: -------------------------------------------------------------------------------- 1 | from occurrence import occurrence 2 | 3 | def test_occurence(): 4 | liste = [1,2,3,4,1,1, 2, 3] 5 | print(occurrence(liste, 1)) #Le 1 est présent 3 fois 6 | print(occurrence(liste, 2)) #Le 2 est présent 2 fois 7 | print(occurrence(liste, 3)) #Le 3 est présent 2 fois 8 | 9 | test_occurrence() 10 | -------------------------------------------------------------------------------- /035. Recréer la méthode join()/pjoin.py: -------------------------------------------------------------------------------- 1 | def pjoin(char, liste): 2 | """Méthode join() des chaînes de caractères recodée en Python""" 3 | final_string = str() 4 | length_char = len(char) 5 | for element in liste: 6 | final_string = final_string + element + char 7 | 8 | if length_char == 0: 9 | return final_string 10 | else: 11 | return final_string[:-length_char] 12 | -------------------------------------------------------------------------------- /035. Recréer la méthode join()/test_pjoin.py: -------------------------------------------------------------------------------- 1 | from pjoin import pjoin 2 | 3 | def test_pjoin(): 4 | liste = ["F", "o", "x", "x,", "p", "y"] 5 | print(pjoin("", liste)) 6 | print(pjoin("-", liste)) 7 | print(pjoin(" ", liste)) 8 | print(pjoin("xxx", liste)) 9 | print(pjoin("Danseaveclesstars", liste)) 10 | 11 | test_pjoin() 12 | -------------------------------------------------------------------------------- /036. Déterminer si une année est bissextile/bissextile.py: -------------------------------------------------------------------------------- 1 | def bissextile(annee): 2 | if((annee%4==0 and annee%100!=0) or annee%400==0): 3 | return True 4 | else: 5 | return False 6 | 7 | 8 | -------------------------------------------------------------------------------- /036. Déterminer si une année est bissextile/test_bissextile.py: -------------------------------------------------------------------------------- 1 | from bissextile import bissextile 2 | 3 | def test_bissextile(): 4 | print("2000 : ", bissextile(2000)) 5 | print("1900 : ", bissextile(1900)) 6 | print("331 : ", bissextile(331)) 7 | print("1 : ", bissextile(1)) 8 | print("1800 : ",bissextile(1800)) 9 | print("16 : ", bissextile(16)) 10 | print("100 : ",bissextile(100)) 11 | print("2020 : ", bissextile(2020)) 12 | print("0: ", bissextile(0)) 13 | print("-4 : ", bissextile(-4)) 14 | test_bissextile() 15 | -------------------------------------------------------------------------------- /037. Convertir des secondes en heures, minutes, secondes/convert_seconds.py: -------------------------------------------------------------------------------- 1 | def convert_seconds(seconde): 2 | """Convertit des secondes en heures, minutes, secondes 3 | Renvoie trois nombres entiers : heure, minute et seconde""" 4 | 5 | heure = seconde // 3600 6 | seconde = seconde - heure*3600 7 | 8 | minute = seconde // 60 9 | seconde = seconde - minute*60 10 | 11 | return heure, minute, seconde 12 | -------------------------------------------------------------------------------- /037. Convertir des secondes en heures, minutes, secondes/test_convert_seconds.py: -------------------------------------------------------------------------------- 1 | from convert_seconds import convert_seconds 2 | 3 | def test_convert_seconds(): 4 | h, m ,s = convert_seconds(360) 5 | print("360 : ", h, " heures, ", m, " minutes, ", s, " seconde") 6 | 7 | h, m ,s = convert_seconds(60) 8 | print("60 : ", h, " heures, ", m, " minutes, ", s, " seconde") 9 | 10 | h, m ,s = convert_seconds(3600) 11 | print("3600 : ", h, " heures, ", m, " minutes, ", s, " seconde") 12 | 13 | h, m ,s = convert_seconds(3601) 14 | print("3601 : ", h, " heures, ", m, " minutes, ", s, " seconde") 15 | 16 | h, m ,s = convert_seconds(10000) 17 | print("10000 : ", h, " heures, ", m, " minutes, ", s, " secondes") 18 | 19 | h, m ,s = convert_seconds(45) 20 | print("45 : ", h, " heures, ", m, " minutes, ", s, " seconde") 21 | 22 | h, m ,s = convert_seconds(7442) 23 | print("7442 : ", h, " heures, ", m, " minutes, ", s, " seconde") 24 | 25 | h, m ,s = convert_seconds(64) 26 | print("64 : ", h, " heures, ", m, " minutes, ", s, " seconde") 27 | 28 | h, m ,s = convert_seconds(122000) 29 | print("122000 : ", h, " heures, ", m, " minutes, ", s, " seconde") 30 | 31 | h, m ,s = convert_seconds(6845) 32 | print("6845 : ", h, " heures, ", m, " minutes, ", s, " secondes") 33 | 34 | test_convert_seconds() 35 | -------------------------------------------------------------------------------- /038. Les cycles avec le modulo/distribution_carte.py: -------------------------------------------------------------------------------- 1 | joueurs = ["Sarah", "Lucie", "Antoine", "Olivier"] 2 | 3 | #Boucle de distribution des cartes depuis un jeu de 52 cartes 4 | for i in range(52): 5 | print("{}. Une carte est distribuée à {}".format(i%4, joueurs[i%4])) 6 | 7 | #Permet d'ajouter un espacement toutes les 4 lignes 8 | if i%4 == 3: 9 | print() 10 | 11 | -------------------------------------------------------------------------------- /038. Les cycles avec le modulo/jour_de_la_semaine.py: -------------------------------------------------------------------------------- 1 | jour_de_la_semaine = ["Lundi", #indice 0 2 | "Mardi", #indice 1 3 | "Mercredi", #indice 2 4 | "Jeudi", #indice 3 5 | "Vendredi", #indice 4 6 | "Samedi", #indice 5 7 | "Dimanche"] #indice 6 8 | 9 | 10 | #Boucle permettant d'illustrer les cycles au sein de l'utilisation de l'opérateur 11 | #modulo 12 | for i in range(100): 13 | print("{} : {}".format(i%7, jour_de_la_semaine[i%7])) 14 | 15 | -------------------------------------------------------------------------------- /039. Obtenir les valeurs dans la table ascii/ascii.py: -------------------------------------------------------------------------------- 1 | def afficher_alphabet(majuscule=True, endprint=True): 2 | """Affiche les lettres de l'alphabet. En majuscule si majuscule == True, 3 | en minuscule sinon. 4 | Ajoute un espace à la fin si endprint == True.""" 5 | 6 | start = 65 if majuscule else 97 7 | for i in range(26): 8 | print(chr(start+i), end="") 9 | 10 | if endprint: 11 | print() 12 | 13 | 14 | 15 | def return_alphabet(majuscule=True): 16 | """Renvoie une liste contenant toutes les lettres de l'alphabet""" 17 | 18 | start = 65 if majuscule else 97 19 | alphabet = list() 20 | for i in range(26): 21 | alphabet.append(chr(start+i)) 22 | 23 | return alphabet 24 | -------------------------------------------------------------------------------- /039. Obtenir les valeurs dans la table ascii/code_ascii_accent.py: -------------------------------------------------------------------------------- 1 | #Liste des lettres avec un accent 2 | accents = ["à", "â", "ä", 3 | "ù","ü","û", 4 | "é","è","ê", "ë", 5 | "ô","ö"] 6 | 7 | #Affichage du code ascii en minuscule et en majuscule des lettres avec un accent 8 | for accent in accents: 9 | print("{} - code ascii : {} - Majuscule : {} - code ascii majuscule : {}".format( 10 | accent, ord(accent), accent.upper(), ord(accent.upper()))) 11 | 12 | 13 | #Recherche d'un pattern entre les minuscules et les majuscules 14 | print("\n\n") 15 | for accent in accents: 16 | print("{} - {} : {}".format(accent, accent.upper(), ord(accent)-ord(accent.upper()))) 17 | -------------------------------------------------------------------------------- /040. Le chiffre de César/cesar.py: -------------------------------------------------------------------------------- 1 | def cryptage(cle, lettre): 2 | """Encode une lettre grâce à une clé. L'encodage est le déplacement 3 | de la lettre dans l'alphabet par rapport à la valeur de la clé""" 4 | 5 | #Si la lettre est en majuscule 6 | if 65 <= ord(lettre) <= 90: 7 | return chr(65 + (ord(lettre)-65+cle) % 26) 8 | 9 | #Si la lettre est en minuscule 10 | elif 97 <= ord(lettre) <= 122: 11 | return chr(97 + (ord(lettre)-97+cle) % 26) 12 | 13 | #Si ce n'est pas une lettre 14 | else: 15 | return lettre 16 | 17 | 18 | 19 | def cesar(cle, mot): 20 | """Encode un mot avec le chiffre de César""" 21 | 22 | mot_crypte = "" 23 | for lettre in mot: 24 | mot_crypte += cryptage(cle, lettre) 25 | 26 | return mot_crypte 27 | -------------------------------------------------------------------------------- /040. Le chiffre de César/test_cesar.py: -------------------------------------------------------------------------------- 1 | from cesar import * 2 | 3 | def test_cesar(): 4 | print(cesar(1, "abcdefghijklmnopqrstuvwxyz")) 5 | print(cesar(25, "ABCDEFGHIJKLMNOPQRSTUVWXYZ3")) 6 | print(cesar(2, "Félix")) 7 | print(cesar(7, "J'aime les hamburgers faits maison")) 8 | 9 | test_cesar() 10 | -------------------------------------------------------------------------------- /041. Résoudre une équation du premier degré/solve_equation.py: -------------------------------------------------------------------------------- 1 | #Pour une équation sous la forme ax+b=c, avec a différent de 0 2 | 3 | def equation(a,b,c): 4 | """Résout une équation de degré 1 sous la forme ax+b=c""" 5 | solution = 0 6 | try: 7 | solution = (c-b)/a 8 | print("La solution est : {}".format(solution)) 9 | 10 | except ZeroDivisionError: 11 | print("a doit être différent de 0 :)") 12 | -------------------------------------------------------------------------------- /041. Résoudre une équation du premier degré/test_solve_equation.py: -------------------------------------------------------------------------------- 1 | from solve_equation import equation 2 | 3 | def test_equation(): 4 | equation(2, 4, 6) 5 | equation(4, 16, 28) 6 | equation(1/2, 0, 1/4) 7 | equation(0, 0, 1) 8 | 9 | test_equation() 10 | -------------------------------------------------------------------------------- /042. Tester si une chaîne de caractères ne contient que des nombres/fonctionnement_isnumeric.py: -------------------------------------------------------------------------------- 1 | texte_sans_nombre = "Bonjour à tous!" 2 | texte_melange_nombre_char = "Bonjour à vous 2!" 3 | texte_nombre = "42" 4 | texte_plusieurs_nombres = "65 48 98 72" 5 | 6 | print(texte_sans_nombre.isnumeric()) #False 7 | print(texte_melange_nombre_char.isnumeric()) #False 8 | print(texte_nombre.isnumeric()) #True 9 | print(texte_plusieurs_nombres.isnumeric()) #False 10 | 11 | #La méthode isnumeric() teste si il n'y a que des chiffres dans la chaîne de 12 | #caractères sans aucun autre caractère, pas même les caractères spéciaux ou l'espace. 13 | -------------------------------------------------------------------------------- /042. Tester si une chaîne de caractères ne contient que des nombres/is_numeric.py: -------------------------------------------------------------------------------- 1 | def is_numeric(text): 2 | """Renvoie True si une chaîne de caractères ne contient que des nombres. 3 | Sinon renvoie False.""" 4 | 5 | text_is_numeric = True 6 | for char in text: 7 | if not 47 < ord(char) < 58: 8 | text_is_numeric = False 9 | break 10 | 11 | return text_is_numeric 12 | -------------------------------------------------------------------------------- /042. Tester si une chaîne de caractères ne contient que des nombres/test_is_numeric.py: -------------------------------------------------------------------------------- 1 | from is_numeric import is_numeric 2 | 3 | def test_is_numeric(): 4 | texte_sans_nombre = "Bonjour à tous!" 5 | texte_melange_nombre_char = "Bonjour à vous 2!" 6 | texte_nombre = "42" 7 | texte_plusieurs_nombres = "18 65 48 98 72" 8 | 9 | print(is_numeric(texte_sans_nombre)) #False 10 | print(is_numeric(texte_melange_nombre_char)) #False 11 | print(is_numeric(texte_nombre)) #True 12 | print(is_numeric(texte_plusieurs_nombres)) #False 13 | 14 | test_is_numeric() 15 | -------------------------------------------------------------------------------- /043. Tester si tous les mots d'une chaîne de caractères commencent par une majuscule/fonctionnement_istitle.py: -------------------------------------------------------------------------------- 1 | texte_chaque_mot_commence_par_une_majuscule = "Bonjour A Tous Les Amis!" 2 | texte_sans_majuscule = "bonjour à tous!" 3 | texte_avec_des_nombres = "Vous Venez Tous Les 3?" 4 | texte_avec_des_nombres_2 = "Ils Ont 3 Chiens Et 2 Chats!" 5 | texte_entierement_majuscule = "JE CRIE TRES TRES FORT!" 6 | texte_apostrophe_minuscule = "l'alien Est Descendu Sur La Terre" 7 | texte_apostrophe_minuscule_majuscule = "l'Alien Est Descendu Sur La Terre" 8 | texte_apostrophe_majuscule = "L'Alien Est Descendu Sur La Terre" 9 | texte_nimporte_comment = "JE VouS AdoRE!" 10 | texte_avec_tirets = "Peut-être Que Tu Es Malade." 11 | texte_avec_tirets_majuscule = "Peut-Etre Que Tu Es Malade." 12 | 13 | print(texte_chaque_mot_commence_par_une_majuscule.istitle()) #True 14 | print(texte_sans_majuscule.istitle()) #False 15 | print(texte_avec_des_nombres.istitle()) #True 16 | print(texte_avec_des_nombres_2.istitle()) #True 17 | print(texte_entierement_majuscule.istitle()) #False 18 | print(texte_apostrophe_minuscule.istitle()) #False 19 | print(texte_apostrophe_minuscule_majuscule.istitle()) #False 20 | print(texte_apostrophe_majuscule.istitle()) #True 21 | print(texte_nimporte_comment.istitle()) #False 22 | print(texte_avec_tirets.istitle()) #False 23 | print(texte_avec_tirets_majuscule.istitle()) #True 24 | -------------------------------------------------------------------------------- /043. Tester si tous les mots d'une chaîne de caractères commencent par une majuscule/is_title.py: -------------------------------------------------------------------------------- 1 | def is_title(text): 2 | """Renvoie True si tous les mots de text commencent par une majuscule""" 3 | text_is_title = True 4 | must_be_uppercase = True 5 | punctuation = [".", " ", ";", ":", "!", "?", ".", "/", "§", "-", "_", "'", '"', 6 | "1", "2", "3", "4", "5", "6", "7", "8", "9"] 7 | 8 | for char in text: 9 | if must_be_uppercase and not 64 < ord(char) < 91 and not char in punctuation: 10 | text_is_title = False 11 | break 12 | 13 | elif not must_be_uppercase and 64 < ord(char) < 91: 14 | text_is_title = False 15 | break 16 | 17 | #Si on vient de rencontrer une ponctuation, la lettre suivante doit être une lettre majuscule 18 | if char in punctuation: 19 | must_be_uppercase = True 20 | 21 | #Sinon c'est qu'on vient de rencontrer une lettre, et donc les autres lettres doivent être en minuscule 22 | else: 23 | must_be_uppercase = False 24 | 25 | return text_is_title 26 | -------------------------------------------------------------------------------- /043. Tester si tous les mots d'une chaîne de caractères commencent par une majuscule/test_is_title.py: -------------------------------------------------------------------------------- 1 | from is_title import is_title 2 | 3 | def test_is_title(): 4 | texte_chaque_mot_commence_par_une_majuscule = "Bonjour A Tous Les Amis!" 5 | texte_sans_majuscule = "bonjour à tous!" 6 | texte_avec_des_nombres = "Vous Venez Tous Les 3?" 7 | texte_avec_des_nombres_2 = "Ils Ont 3 Chiens Et 2 Chats!" 8 | texte_entierement_majuscule = "JE CRIE TRES TRES FORT!" 9 | texte_apostrophe_minuscule = "l'alien Est Descendu Sur La Terre" 10 | texte_apostrophe_minuscule_majuscule = "l'Alien Est Descendu Sur La Terre" 11 | texte_apostrophe_majuscule = "L'Alien Est Descendu Sur La Terre" 12 | texte_nimporte_comment = "JE VouS AdoRE!" 13 | texte_avec_tirets = "Peut-être Que Tu Es Malade." 14 | texte_avec_tirets_majuscule = "Peut-Etre Que Tu Es Malade." 15 | 16 | print(is_title(texte_chaque_mot_commence_par_une_majuscule)) 17 | print(is_title(texte_sans_majuscule)) 18 | print(is_title(texte_avec_des_nombres)) 19 | print(is_title(texte_avec_des_nombres_2)) 20 | print(is_title(texte_entierement_majuscule)) 21 | print(is_title(texte_apostrophe_minuscule)) 22 | print(is_title(texte_apostrophe_minuscule_majuscule)) 23 | print(is_title(texte_apostrophe_majuscule)) 24 | print(is_title(texte_nimporte_comment)) 25 | print(is_title(texte_avec_tirets)) 26 | print(is_title(texte_avec_tirets_majuscule)) 27 | 28 | test_is_title() 29 | -------------------------------------------------------------------------------- /044. Renvoyer une chaîne de caractères entièrement en minuscule ou majuscule/code_ascii_accent.py: -------------------------------------------------------------------------------- 1 | #Liste des lettres avec un accent 2 | accents = ["à", "â", "ä", 3 | "ù","ü","û", 4 | "é","è","ê", "ë", 5 | "ô","ö"] 6 | 7 | #Affichage du code ascii en minuscule et en majuscule des lettres avec un accent 8 | for accent in accents: 9 | print("{} - code ascii : {} - Majuscule : {} - code ascii majuscule : {}".format( 10 | accent, ord(accent), accent.upper(), ord(accent.upper()))) 11 | 12 | 13 | #Recherche d'un pattern entre les minuscules et les majuscules 14 | print("\n\n") 15 | for accent in accents: 16 | print("{} - {} : {}".format(accent, accent.upper(), ord(accent)-ord(accent.upper()))) 17 | 18 | for accent in accents: 19 | print("{}".format(accent.upper())) 20 | -------------------------------------------------------------------------------- /044. Renvoyer une chaîne de caractères entièrement en minuscule ou majuscule/lower_upper.py: -------------------------------------------------------------------------------- 1 | #Déclaration des variables 2 | string_avec_majuscule_et_minuscule = "Bonjour à tous!" 3 | string_majuscule = "BONJOUR A TOUS!" 4 | string_minuscule = "bonjour à tous!" 5 | string_ponctuation = "Bonjour! Vous allez bien? Moi... oui!" 6 | string_chiffre = "J'ai 3 chats. Et vous?" 7 | 8 | #Mise en minuscule avec lower() 9 | print("----- LOWER -----") 10 | 11 | print(string_avec_majuscule_et_minuscule.lower()) 12 | print(string_majuscule.lower()) 13 | print(string_minuscule.lower()) 14 | print(string_ponctuation.lower()) 15 | print(string_chiffre.lower()) 16 | 17 | 18 | #Mise en majuscule avec upper() 19 | print("\n----- UPPER -----") 20 | 21 | print(string_avec_majuscule_et_minuscule.upper()) 22 | print(string_majuscule.upper()) 23 | print(string_minuscule.upper()) 24 | print(string_ponctuation.upper()) 25 | print(string_chiffre.upper()) 26 | -------------------------------------------------------------------------------- /044. Renvoyer une chaîne de caractères entièrement en minuscule ou majuscule/plower_pupper.py: -------------------------------------------------------------------------------- 1 | def plower(string): 2 | """Renvoie la chaîne de caractères string entièrement en minuscule""" 3 | new_string = "" 4 | for lettre in string: 5 | #Si la lettre est en majuscule 6 | if 65 <= ord(lettre) <= 90: 7 | new_string += chr(ord(lettre)+32) 8 | 9 | #Si c'est une lettre avec un accent 10 | elif lettre in ["À","Â","Ä","Ù","Ü","Û","É","È","Ê","Ë","Ô","Ö"]: 11 | new_string += chr(ord(lettre)+32) 12 | 13 | else: 14 | new_string += lettre 15 | 16 | return new_string 17 | 18 | def pupper(string): 19 | """Renvoie la chaîne de caractères string entièrement en minuscule""" 20 | new_string = "" 21 | for lettre in string: 22 | #Si la lettre est en minuscule 23 | if 97 <= ord(lettre) <= 122: 24 | new_string += chr(ord(lettre)-32) 25 | 26 | #Si c'est une lettre avec un accent 27 | elif lettre in ["à", "â", "ä","ù","ü","û","é","è","ê", "ë","ô","ö"]: 28 | new_string += chr(ord(lettre)-32) 29 | 30 | else: 31 | new_string += lettre 32 | 33 | return new_string 34 | -------------------------------------------------------------------------------- /044. Renvoyer une chaîne de caractères entièrement en minuscule ou majuscule/test_plower_pupper.py: -------------------------------------------------------------------------------- 1 | from plower_pupper import plower, pupper 2 | 3 | def test_upper_lower(): 4 | #Déclaration des variables 5 | string_avec_majuscule_et_minuscule = "Bonjour à tous!" 6 | string_majuscule = "BONJOUR A TOUS!" 7 | string_minuscule = "bonjour à tous!" 8 | string_ponctuation = "Bonjour! Vous allez bien? Moi... oui!" 9 | string_chiffre = "J'ai 3 chats. Et vous?" 10 | 11 | #Test de pupper() et plower() 12 | print(pupper(string_avec_majuscule_et_minuscule)) 13 | print(plower(string_avec_majuscule_et_minuscule)) 14 | print() 15 | 16 | print(pupper(string_majuscule)) 17 | print(plower(string_majuscule)) 18 | print() 19 | 20 | print(pupper(string_minuscule)) 21 | print(plower(string_minuscule)) 22 | print() 23 | 24 | print(pupper(string_ponctuation)) 25 | print(plower(string_ponctuation)) 26 | print() 27 | 28 | print(pupper(string_chiffre)) 29 | print(plower(string_chiffre)) 30 | print() 31 | 32 | test_upper_lower() 33 | -------------------------------------------------------------------------------- /045. Enlever les doublons dans une liste/no_order_doublon.py: -------------------------------------------------------------------------------- 1 | #Si l'ordre de la liste n'importe pas, il suffit de caster la liste en set, 2 | #puis de la recaster en liste. 3 | 4 | def enlever_doublon(liste): 5 | """Enlève les doublons dans une liste mais ne conserve pas forcément les éléments 6 | dans leur ordre d'apparition""" 7 | 8 | return list(set(liste)) 9 | -------------------------------------------------------------------------------- /045. Enlever les doublons dans une liste/order_doublon.py: -------------------------------------------------------------------------------- 1 | def doublon(liste): 2 | """Enlève les doublons dans une liste en conservant l'ordre d'apparition 3 | des éléments""" 4 | liste_sans_doublon = list() 5 | for element in liste: 6 | if not element in liste_sans_doublon: 7 | liste_sans_doublon.append(element) 8 | 9 | return liste_sans_doublon 10 | -------------------------------------------------------------------------------- /045. Enlever les doublons dans une liste/test_order_doublon.py: -------------------------------------------------------------------------------- 1 | from order_doublon import doublon 2 | from no_order_doublon import enlever_doublon 3 | 4 | liste = [1,1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,5,5] 5 | liste_nom = ["Sarah", "Sarah", "Sarah", "Antoine", "Filip", "Filip"] 6 | print(doublon(liste)) 7 | print(doublon(liste_nom)) 8 | print(enlever_doublon(liste)) 9 | print(enlever_doublon(liste_nom)) 10 | -------------------------------------------------------------------------------- /046. Tester si une chaîne de caractères contient uniquement des lettres de l'alphabet/only_alphabet.py: -------------------------------------------------------------------------------- 1 | def only_alphabet(string): 2 | """Teste si une chaîne de caractères ne contient que des lettres de l'alphabet""" 3 | 4 | for char in string: 5 | #Si c'est pas une majuscule, ni une minuscule, ni une lettre avec accent 6 | if not 65 <= ord(char) <= 90 and \ 7 | not 97 <= ord(char) <= 122 and \ 8 | not 192 <= ord(char) <= 214 and \ 9 | not 216 <= ord(char) <= 254: 10 | return False 11 | 12 | return True 13 | -------------------------------------------------------------------------------- /046. Tester si une chaîne de caractères contient uniquement des lettres de l'alphabet/python_isalpha.py: -------------------------------------------------------------------------------- 1 | #Fonctionnement de la méthode isalpha() issue des chaînes de caractères. 2 | #Cette méthode teste si tous les caractères d'une chaîne de caractères sont 3 | #des lettres de l'alphabet. 4 | 5 | pseudonyme1 = "Foxxpy" 6 | pseudonyme2 = "Foxxpy68" 7 | prenom = "Félix" 8 | phrase = "Bonjour. Vous allez bien?" 9 | 10 | print(pseudonyme1.isalpha()) #True 11 | print(pseudonyme2.isalpha()) #False 12 | print(prenom.isalpha()) #True 13 | print(phrase.isalpha()) #False 14 | -------------------------------------------------------------------------------- /046. Tester si une chaîne de caractères contient uniquement des lettres de l'alphabet/test_only_alphabet.py: -------------------------------------------------------------------------------- 1 | from only_alphabet import only_alphabet 2 | 3 | def test_only_alphabet(): 4 | pseudonyme1 = "Foxxpy" 5 | pseudonyme2 = "Foxxpy68" 6 | prenom = "Félix" 7 | phrase = "Bonjour. Vous allez bien?" 8 | 9 | print(only_alphabet(pseudonyme1)) #True 10 | print(only_alphabet(pseudonyme2)) #False 11 | print(only_alphabet(prenom)) #True 12 | print(only_alphabet(phrase)) #False 13 | 14 | test_only_alphabet() 15 | -------------------------------------------------------------------------------- /047. Somme de tous les éléments d'un dictionnaire/sum_dict.py: -------------------------------------------------------------------------------- 1 | def sum_dict(dictionnaire): 2 | """Effectue la somme des valeurs des éléments d'un dictionnaire""" 3 | 4 | return sum(dictionnaire.values()) 5 | -------------------------------------------------------------------------------- /047. Somme de tous les éléments d'un dictionnaire/test_sum_dict.py: -------------------------------------------------------------------------------- 1 | from sum_dict import sum_dict 2 | 3 | def test_sum_dict(): 4 | 5 | #Prix en boulangerie 6 | dictionnaire = {"Baguette" : 0.85, 7 | "Pain au chocolat" : 1.10, 8 | "Croissant" : 1.00, 9 | "Tradition" : 1.05 10 | } 11 | 12 | #Comptes en banque 13 | dictionnaire_2 = { 14 | "Sarah" : 10, 15 | "Lucie" : 30, 16 | "Antoine" : 40, 17 | "Marc" : 5, 18 | "Sylvester" : 15 19 | 20 | } 21 | 22 | #Somme des éléments des dictionnaires instanciés 23 | print(sum_dict(dictionnaire)) 24 | print(sum_dict(dictionnaire_2)) 25 | 26 | test_sum_dict() 27 | -------------------------------------------------------------------------------- /048. Fusionner deux dictionnaires/__pycache__/merge_dict.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/foxxpy/Algorithmie/098b9f339400ca642b698d53df953ceb1fa9fe67/048. Fusionner deux dictionnaires/__pycache__/merge_dict.cpython-38.pyc -------------------------------------------------------------------------------- /048. Fusionner deux dictionnaires/merge_dict.py: -------------------------------------------------------------------------------- 1 | def merge_dict(dict1, dict2): 2 | """Fusionne deux dictionnaires""" 3 | 4 | final_dict = dict1.copy() 5 | final_dict.update(dict2) 6 | return final_dict 7 | 8 | 9 | 10 | def merge_dict_for(dict1, dict2): 11 | """Fusionne deux dictionnaires grâce à une boucle for""" 12 | 13 | final_dict = dict() 14 | for dictionnaire in [dict1,dict2]: 15 | for key, value in dictionnaire.items(): 16 | final_dict[key] = value 17 | 18 | return final_dict 19 | -------------------------------------------------------------------------------- /048. Fusionner deux dictionnaires/test_merge_dict.py: -------------------------------------------------------------------------------- 1 | from merge_dict import merge_dict, merge_dict_for 2 | 3 | def test_merge_dict(): 4 | 5 | #Clients d'une banque 6 | client1 = {"Fabrice" : 1000.85, "Jérome" : 2400.00} 7 | client2 = {"Clémentine" : -124.00, "Capucine" : 3762.00, "Sarah" : 685.24} 8 | print(merge_dict(client1, client2)) 9 | print(merge_dict_for(client1, client2)) 10 | 11 | print() 12 | #Sportifs 13 | sport1 = {"Henry" : "Football", "Emmy" : "Karaté", "Martin" : "Rugby"} 14 | sport2 = {"Jenny" : "Boxe", "Alain" : "Danse classique"} 15 | print(merge_dict(sport1, sport2)) 16 | print(merge_dict_for(sport1, sport2)) 17 | 18 | print() 19 | #Test avec une clé similaire dans chaque dictionnaire 20 | test1 = {"1" : 1, "2" : 2} 21 | test2 = {"1" : 3} 22 | print(merge_dict(test1, test2)) 23 | print(merge_dict_for(test1, test2)) 24 | 25 | test_merge_dict() 26 | -------------------------------------------------------------------------------- /049. Multiplier toutes les valeurs d'un dictionnaire/multi_dict.py: -------------------------------------------------------------------------------- 1 | def new_multiply_value(dictionnaire, value): 2 | """Multiplie toutes les valeurs d'un dictionnaire. 3 | Renvoie un nouveau dictionnaire""" 4 | 5 | nouveau_dictionnaire = dictionnaire.copy() 6 | for key in nouveau_dictionnaire.keys(): 7 | nouveau_dictionnaire[key] = nouveau_dictionnaire[key] * value 8 | 9 | return nouveau_dictionnaire 10 | 11 | 12 | 13 | def multiply_value(dictionnaire, value): 14 | """Multiplie toutes les valeurs d'un dictionnaire. 15 | Change le dictionnaire envoyé en paramètre""" 16 | 17 | for key in dictionnaire.keys(): 18 | dictionnaire[key] = dictionnaire[key] * value 19 | 20 | return dictionnaire 21 | -------------------------------------------------------------------------------- /049. Multiplier toutes les valeurs d'un dictionnaire/test_multi_dict.py: -------------------------------------------------------------------------------- 1 | from multi_dict import * 2 | 3 | 4 | 5 | def test_new_multiply_value(): 6 | 7 | #Promotion appliquée sur tous les articles d'un magasin de vêtements 8 | prix_de_vente = {"Jean" : 35.00, "Veste" : 55.00, "Caleçon" : 8.00, "Chaussettes" : 4.00} 9 | promotion = new_multiply_value(prix_de_vente, 0.80) 10 | print(prix_de_vente) 11 | print(promotion) 12 | 13 | print() 14 | #Buff qui multiplie par 2 la force des personnages du groupe 15 | heros = {"Luciferas" : 25, "Luffy" : 40, "Magicarpe" : 1} 16 | heros_buff = new_multiply_value(heros, 2) 17 | print(heros) 18 | print(heros_buff) 19 | 20 | 21 | 22 | def test_multiply_value(): 23 | 24 | #Promotion appliquée sur tous les articles d'un magasin de vêtements 25 | prix_de_vente = {"Jean" : 35.00, "Veste" : 55.00, "Caleçon" : 8.00, "Chaussettes" : 4.00} 26 | promotion = multiply_value(prix_de_vente, 0.80) 27 | print(prix_de_vente) 28 | print(promotion) 29 | 30 | print() 31 | #Buff qui multiplie par 2 la force des personnages du groupe 32 | heros = {"Luciferas" : 25, "Luffy" : 40, "Magicarpe" : 1} 33 | heros_buff = multiply_value(heros, 2) 34 | print(heros) 35 | print(heros_buff) 36 | 37 | 38 | 39 | test_new_multiply_value() 40 | print() 41 | test_multiply_value() 42 | -------------------------------------------------------------------------------- /050. Trouver la valeur maximale d'un dictionnaire/max_dict.py: -------------------------------------------------------------------------------- 1 | def max_dict(dictionnaire): 2 | """Retourne la valeur maximale d'un dictionnaire""" 3 | 4 | max_value = 0 5 | for i, value in enumerate(dictionnaire.values()): 6 | if i == 0 or value > max_value: 7 | max_value = value 8 | 9 | return max_value 10 | -------------------------------------------------------------------------------- /050. Trouver la valeur maximale d'un dictionnaire/test_max_dict.py: -------------------------------------------------------------------------------- 1 | from max_dict import max_dict 2 | 3 | 4 | 5 | def test_max_dict(): 6 | 7 | #Argent de poche 8 | dictionnaire = {"Alfred" : 100, "Julie" : 150, "Antoine" : 20} 9 | print(max_dict(dictionnaire)) 10 | 11 | #Magasin de luxe 12 | luxe = {"Bague" : 3200, "Montre" : 5600, "Sac à main" : 1400} 13 | print(max_dict(luxe)) 14 | 15 | 16 | 17 | test_max_dict() 18 | -------------------------------------------------------------------------------- /051. Trouver la valeur minimale d'un dictionnaire/min_dict.py: -------------------------------------------------------------------------------- 1 | def min_dict(dictionnaire): 2 | """Retourne la valeur minimale d'un dictionnaire""" 3 | 4 | min_value = 0 5 | for i, value in enumerate(dictionnaire.values()): 6 | if i == 0 or value < min_value: 7 | min_value = value 8 | 9 | return min_value 10 | -------------------------------------------------------------------------------- /051. Trouver la valeur minimale d'un dictionnaire/test_min_dict.py: -------------------------------------------------------------------------------- 1 | from min_dict import min_dict 2 | 3 | 4 | def test_min_dict(): 5 | 6 | #Argent de poche 7 | dictionnaire = {"Alfred" : 100, "Julie" : 150, "Antoine" : 20} 8 | print(min_dict(dictionnaire)) 9 | 10 | #Magasin de luxe 11 | luxe = {"Bague" : 3200, "Montre" : 5600, "Sac à main" : 1400} 12 | print(min_dict(luxe)) 13 | 14 | 15 | 16 | test_min_dict() 17 | -------------------------------------------------------------------------------- /052. Transformer deux listes en un dictionnaire/test_two_lists_to_dict.py: -------------------------------------------------------------------------------- 1 | from two_lists_to_dict import two_lists_to_dict 2 | 3 | def test_two_lists_to_dict(): 4 | 5 | #Des personnes et l'argent dans leur porte-monnaie 6 | liste1 = ["Marc", "Antoine", "Cyril"] 7 | liste2 = [20, 60, 80] 8 | print(two_lists_to_dict(liste1, liste2)) 9 | 10 | #Deux listes de longueur différente 11 | nombre1 = [1,2,3,4] 12 | nombre2 = [1,2,3] 13 | print(two_lists_to_dict(nombre1, nombre2)) 14 | 15 | 16 | 17 | test_two_lists_to_dict() 18 | -------------------------------------------------------------------------------- /052. Transformer deux listes en un dictionnaire/two_lists_to_dict.py: -------------------------------------------------------------------------------- 1 | def two_lists_to_dict(liste1, liste2): 2 | """Fusionne deux listes pour les renvoyer dans un dictionnaire 3 | Les éléments de la première liste seront les clés du dictionnaire. 4 | Les éléments de la seconde liste seront les valeurs du dictionnaire""" 5 | 6 | #Si les listes n'ont pas la même longueur, on ne renvoie rien 7 | if len(liste1) != len(liste2): 8 | return None 9 | 10 | else: 11 | dictionnaire = dict() 12 | for i in range(len(liste1)): 13 | dictionnaire[liste1[i]] = liste2[i] 14 | 15 | return dictionnaire 16 | -------------------------------------------------------------------------------- /053. Supprimer tous les éléments d'une liste/clear.py: -------------------------------------------------------------------------------- 1 | #En python, on peut utiliser la méthode clear() des listes pour supprimer tous 2 | #les éléments 3 | 4 | liste = [1,2,3,4,5,6,7,8,9,10] 5 | liste.clear() 6 | print(liste) 7 | -------------------------------------------------------------------------------- /053. Supprimer tous les éléments d'une liste/pclear.py: -------------------------------------------------------------------------------- 1 | def pclear(liste): 2 | """Supprime tous les éléments d'une liste""" 3 | while len(liste) > 0: 4 | liste.pop(0) 5 | 6 | return liste 7 | -------------------------------------------------------------------------------- /053. Supprimer tous les éléments d'une liste/test_pclear.py: -------------------------------------------------------------------------------- 1 | from pclear import * 2 | 3 | def test_pclear(): 4 | """Test de la méthode pclear()""" 5 | 6 | #La liste garde le même identifiant 7 | liste = [1,2,3,4,5,6,7,8,9,10] 8 | print(id(liste)) 9 | id_pclear(liste) 10 | print(id(liste)) 11 | print(liste) 12 | -------------------------------------------------------------------------------- /054. Afficher les éléments d'un dictionnaire triés par clé/sort_dict.py: -------------------------------------------------------------------------------- 1 | def print_sort_dict(dictionnaire): 2 | """Affiche les éléments d'un dictionnaire triés par leur clé""" 3 | for key in sorted(dictionnaire): 4 | print("{} : {}".format(key, dictionnaire[key])) 5 | 6 | 7 | -------------------------------------------------------------------------------- /054. Afficher les éléments d'un dictionnaire triés par clé/test_sort_dict.py: -------------------------------------------------------------------------------- 1 | from sort_dict import print_sort_dict 2 | 3 | def test_sort_dict(): 4 | dictionnaire = {"c" : 3, "b" : 10, "a" : 456} 5 | print_sort_dict(dictionnaire) 6 | 7 | print() 8 | dictionnaire2 = {"François" : 1000, "Alice" : 2000, "Bob" : 4000} 9 | print_sort_dict(dictionnaire2) 10 | 11 | test_sort_dict() 12 | -------------------------------------------------------------------------------- /055. Supprimer le caractère à l'indice n d'une chaîne de caractères/delete_char.py: -------------------------------------------------------------------------------- 1 | def delete_char(string, n): 2 | """Supprime le caractère à l'indice n de la chaîne de caractères string""" 3 | return string[0:n] + string[n+1:] 4 | -------------------------------------------------------------------------------- /055. Supprimer le caractère à l'indice n d'une chaîne de caractères/test_delete_char.py: -------------------------------------------------------------------------------- 1 | from delete_char import delete_char 2 | 3 | def test_delete_char(): 4 | #En supprimant le caractère à l'indice 2 5 | string = "Foxxpy" 6 | s1 = delete_char("Foxxpy", 2) 7 | print(s1) 8 | 9 | #En supprimant le premier caractère 10 | print() 11 | s2 = delete_char("Foxxpy", 0) 12 | print(s2) 13 | 14 | #En supprimant le dernier caractère 15 | print() 16 | s3 = delete_char("Foxxpy", 5) 17 | print(s3) 18 | 19 | #Indice hors de la chaîne de caractères 20 | print() 21 | s4 = delete_char("Foxxpy", 100) 22 | print(s4) 23 | 24 | #Indice hors de la chaîne de caractères 2 25 | print() 26 | s5 = delete_char("Foxxpy", -600) 27 | print(s5) 28 | 29 | test_delete_char() 30 | -------------------------------------------------------------------------------- /056. Liste - Différence entre remove, pop et del/difference_entre_pop_remove_del.py: -------------------------------------------------------------------------------- 1 | #Remove : retire un élément spécifique de la liste 2 | liste = ["a", "b", "c", "d", "e", "f"] 3 | liste.remove("b") 4 | print(liste) 5 | 6 | #pop : retire un élément à un indice spécifique 7 | liste = ["a", "b", "c", "d", "e", "f"] 8 | liste.pop(2) #retire le c 9 | print(liste) 10 | 11 | #del : supprime un élément à un indice spécifique, mais ce n'est pas une méthode appartenant à la classe List. 12 | liste = ["a", "b", "c", "d", "e", "f"] 13 | del liste[3] #retire le d 14 | print(liste) 15 | -------------------------------------------------------------------------------- /057. Tester si une date est valide/date_is_valid.py: -------------------------------------------------------------------------------- 1 | def bissextile(annee): 2 | """Teste si une année est bissextile ou non.""" 3 | if((annee%4==0 and annee%100!=0) or annee%400==0): 4 | return True 5 | else: 6 | return False 7 | 8 | 9 | 10 | def date_is_valid(jour, mois, annee): 11 | """Teste si une date est valide, et donc, si elle peut exister dans le calendrier""" 12 | fevrier = 29 if bissextile(annee) else 28 13 | jour_dans_le_mois = {1 : 31, 14 | 2 : fevrier, 15 | 3 : 31, 16 | 4 : 30, 17 | 5: 31, 18 | 6 : 30, 19 | 7 : 31, 20 | 8 : 31, 21 | 9 : 30, 22 | 10 : 31, 23 | 11 : 30, 24 | 12 : 31} 25 | 26 | #Si la valeur du mois est compris entre 1 et 12 27 | #Et que le nombre de jour est compris entre 1 et le nombre de jours dans ce mois 28 | if 1<= mois <=12 and \ 29 | 1 <= jour <= jour_dans_le_mois[mois]: 30 | return True 31 | 32 | else: 33 | return False 34 | -------------------------------------------------------------------------------- /057. Tester si une date est valide/test_date_is_valid.py: -------------------------------------------------------------------------------- 1 | from date_is_valid import date_is_valid 2 | 3 | def test_date_is_valid(): 4 | j1, m1, a1 = 20, 2, 2020 5 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 6 | 7 | j1, m1, a1 = 29, 2, 2000 8 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 9 | 10 | j1, m1, a1 = 29, 2, 1900 11 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 12 | 13 | j1, m1, a1 = -4, 5, 2020 14 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 15 | 16 | j1, m1, a1 = 60, 7, 2000 17 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 18 | 19 | j1, m1, a1 = 12, 13, 2020 20 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 21 | 22 | j1, m1, a1 = 1, 0, 2020 23 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 24 | 25 | j1, m1, a1 = 0, 5, 2020 26 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 27 | 28 | j1, m1, a1 = 31, 12, 2020 29 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 30 | 31 | j1, m1, a1 = 30, 8, 2020 32 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 33 | 34 | j1, m1, a1 = 1, 1, 0 35 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 36 | 37 | j1, m1, a1 = 2, 2, 10284 38 | print("{}/{}/{} : {}".format(j1,m1,a1,date_is_valid(j1,m1,a1))) 39 | 40 | 41 | test_date_is_valid() 42 | -------------------------------------------------------------------------------- /058. Inverser un nombre entier/inverser_entier.py: -------------------------------------------------------------------------------- 1 | def inverser_entier(nombre): 2 | 3 | #Si le nombre est négatif, on ajoute un "-" au début de y 4 | if nombre < 0: 5 | return int("-"+str(nombre)[1:][::-1]) 6 | else: 7 | return int(str(nombre)[::-1]) 8 | -------------------------------------------------------------------------------- /058. Inverser un nombre entier/test_inverser_entier.py: -------------------------------------------------------------------------------- 1 | from inverser_entier import inverser_entier 2 | 3 | a = 123456789 #Inverse facile à voir 4 | print(inverser_entier(a)) 5 | 6 | b = 2**31 #grand nombre 7 | print(inverser_entier(b)) 8 | 9 | c = 12521 #palindrome 10 | print(inverser_entier(c)) 11 | 12 | d = -123456789 13 | print(inverser_entier(d)) 14 | 15 | e = -111333555777999 16 | print(inverser_entier(e)) 17 | -------------------------------------------------------------------------------- /059. Convertir un nombre décimal en binaire/decimal_to_binary.py: -------------------------------------------------------------------------------- 1 | def decimal_to_binary(n): 2 | """Convertit un nombre décimal n en un nombre binaire 3 | Renvoie le nombre binaire dans une chaîne de caractères""" 4 | 5 | binary = "" 6 | while n > 0 : 7 | binary = str(n%2) + binary 8 | n = n // 2 9 | 10 | return binary 11 | -------------------------------------------------------------------------------- /059. Convertir un nombre décimal en binaire/test_decimal_to_binary.py: -------------------------------------------------------------------------------- 1 | from decimal_to_binary import * 2 | 3 | #On affiche les 100 premiers nombres binaires 4 | for i in range(100): 5 | print(decimal_to_binary(i)) 6 | -------------------------------------------------------------------------------- /060. Convertir un nombre binaire en décimal/binary_to_decimal.py: -------------------------------------------------------------------------------- 1 | def binary_to_decimal(binary): 2 | """Convertit un nombre en base binaire en un nombre en base décimale""" 3 | 4 | if "0b" in binary: 5 | binary = binary.replace("0b", "") 6 | 7 | total = 0 8 | for i, bit in enumerate(binary[::-1]): 9 | total += int(bit) * 2**i 10 | 11 | return total 12 | -------------------------------------------------------------------------------- /060. Convertir un nombre binaire en décimal/test_binary_to_decimal.py: -------------------------------------------------------------------------------- 1 | from binary_to_decimal import * 2 | 3 | #On convertit les 100 premiers nombres binaires en nombres décimaux 4 | for i in range(100): 5 | i = bin(i) 6 | print(binary_to_decimal(i)) 7 | -------------------------------------------------------------------------------- /061. Convertir un nombre décimal en hexadécimal/decimal_to_hexadecimal.py: -------------------------------------------------------------------------------- 1 | def decimal_to_hexadecimal(n): 2 | """Convertit un nombre décimal en un nombre hexadécimal""" 3 | 4 | hexadecimal = "" 5 | hexa_values = {"0" : "0", "1" : "1", "2" : "2", "3" : "3", "4" : "4", "5" : "5", "6" : "6", 6 | "7" : "7", "8" : "8", "9" : "9", "10" : "A", "11" : "B", "12" : "C", 7 | "13" : "D", "14" : "E", "15" : "F"} 8 | 9 | while n > 0: 10 | hexadecimal = hexa_values[str(n%16)] + hexadecimal 11 | n = n // 16 12 | 13 | return hexadecimal 14 | -------------------------------------------------------------------------------- /061. Convertir un nombre décimal en hexadécimal/test_decimal_to_hexadecimal.py: -------------------------------------------------------------------------------- 1 | from decimal_to_hexadecimal import * 2 | 3 | #On convertit les 100 premiers nombres décimaux en nombres hexadécimaux 4 | for i in range(100): 5 | print(decimal_to_hexadecimal(i)) 6 | -------------------------------------------------------------------------------- /062. Convertir un nombre hexadécimal en nombre décimal/hexadecimal_to_decimal.py: -------------------------------------------------------------------------------- 1 | def hexadecimal_to_decimal(hexadecimal): 2 | """Convertit un nombre hexadecimal en un nombre décimal""" 3 | 4 | hexa_values = {"0" : 0, "1" : 1, "2" : 2, "3" : 3, "4" : 4, "5" : 5, "6" : 6, 5 | "7" : 7, "8" : 8, "9" : 9 , "A" : 10, "B" : 11, "C" : 12, 6 | "D" : 13, "E" : 14, "F" : 15} 7 | 8 | #Si on a 0x dans le nombre hexadécimal, on le retire 9 | if "0x" in hexadecimal: 10 | hexadecimal = hexadecimal.replace("0x", "") 11 | 12 | hexadecimal = hexadecimal.upper() 13 | total = 0 14 | for i, digit in enumerate(hexadecimal[::-1]): 15 | total += hexa_values[digit] * 16**i 16 | 17 | return total 18 | -------------------------------------------------------------------------------- /062. Convertir un nombre hexadécimal en nombre décimal/test_hexadecimal_to_decimal.py: -------------------------------------------------------------------------------- 1 | from hexadecimal_to_decimal import * 2 | 3 | for i in range(100): 4 | i = hex(i) 5 | print(hexadecimal_to_decimal(i)) 6 | -------------------------------------------------------------------------------- /063. Addition de 2 vecteurs/vector_add.py: -------------------------------------------------------------------------------- 1 | def vector_add(vector1, vector2): 2 | """Calcule la somme de deux vecteurs""" 3 | 4 | #Si les vecteurs ont une longueur différentes, on ne peut pas calculer la somme 5 | if len(vector1) != len(vector2): 6 | return None 7 | 8 | new_vector = list() 9 | for i in range(len(vector1)): 10 | new_vector.append(vector1[i] + vector2[i]) 11 | 12 | return new_vector 13 | 14 | 15 | -------------------------------------------------------------------------------- /064. Générer une matrice aléatoire/generer_matrice_aleatoire.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | def afficher_matrice(matrice): 4 | """Affiche la matrice dans la console""" 5 | 6 | for line in matrice: 7 | print(line) 8 | 9 | 10 | 11 | def generer_matrice_aleatoire(M, N, inf=1, sup=100): 12 | """Génère une matrice avec des nombres aléatoire""" 13 | 14 | matrix = [] 15 | 16 | for i in range(M): 17 | line = [] 18 | for j in range(N): 19 | line.append(randint(inf, sup)) 20 | matrix.append(line) 21 | 22 | return matrix 23 | -------------------------------------------------------------------------------- /064. Générer une matrice aléatoire/test_generer_matrice_aleatoire.py: -------------------------------------------------------------------------------- 1 | from generer_matrice_aleatoire import * 2 | 3 | matrice = generer_matrice_aleatoire(2,2,1,10) 4 | afficher_matrice(matrice) 5 | print() 6 | 7 | matrice = generer_matrice_aleatoire(3,3,1,100) 8 | afficher_matrice(matrice) 9 | print() 10 | 11 | matrice = generer_matrice_aleatoire(4,4,1,50) 12 | afficher_matrice(matrice) 13 | print() 14 | 15 | matrice = generer_matrice_aleatoire(3,2,1,10) 16 | afficher_matrice(matrice) 17 | print() 18 | 19 | matrice = generer_matrice_aleatoire(1,4,-5,5) 20 | afficher_matrice(matrice) 21 | print() 22 | -------------------------------------------------------------------------------- /065. Calculer l'aire et le périmètre d'un cercle/circle.py: -------------------------------------------------------------------------------- 1 | from math import pi 2 | 3 | 4 | 5 | def aire_cercle(rayon): 6 | """Calcule l'aire d'un cercle""" 7 | return 2*pi*rayon**2 8 | 9 | 10 | 11 | def perimetre_cercle(rayon): 12 | """Calcule le périmètre d'un cercle""" 13 | return 2*pi*rayon 14 | -------------------------------------------------------------------------------- /065. Calculer l'aire et le périmètre d'un cercle/test_circle.py: -------------------------------------------------------------------------------- 1 | from circle import * 2 | 3 | r = 5 4 | print("Périmètre : {}".format(perimetre_cercle(r))) 5 | print("Aire : {}".format(aire_cercle(r))) 6 | 7 | r = 7 8 | print("Périmètre : {}".format(perimetre_cercle(r))) 9 | print("Aire : {}".format(aire_cercle(r))) 10 | 11 | r = 8 12 | print("Périmètre : {}".format(perimetre_cercle(r))) 13 | print("Aire : {}".format(aire_cercle(r))) 14 | 15 | r = 1 16 | print("Périmètre : {}".format(perimetre_cercle(r))) 17 | print("Aire : {}".format(aire_cercle(r))) 18 | -------------------------------------------------------------------------------- /066. Calculer l'aire et le périmètre d'un triangle/test_triangle.py: -------------------------------------------------------------------------------- 1 | from triangle import * 2 | 3 | ab, bc, ca = 3, 3, 2 4 | print("Périmètre : {}".format(perimetre_triangle(ab,bc,ca))) 5 | 6 | ab, bc, ca = 5, 4, 3 7 | print("Périmètre : {}".format(perimetre_triangle(ab,bc,ca))) 8 | 9 | ab, bc, ca = 6, 7, 8 10 | print("Périmètre : {}".format(perimetre_triangle(ab,bc,ca))) 11 | 12 | b, h = 4, 3 13 | print("Aire : {}".format(b, h)) 14 | 15 | b, h = 6, 9 16 | print("Aire : {}".format(b, h)) 17 | 18 | b, h = 1, 2 19 | print("Aire : {}".format(b, h)) 20 | 21 | b, h = 2.5, 4 22 | print("Aire : {}".format(b, h)) 23 | -------------------------------------------------------------------------------- /066. Calculer l'aire et le périmètre d'un triangle/triangle.py: -------------------------------------------------------------------------------- 1 | def perimetre_triangle(ab,bc,ca): 2 | """Calcule le périmètre d'un triangle""" 3 | return ab+bc+ca 4 | 5 | 6 | 7 | def aire_triangle(b, h): 8 | """Calcule l'aire d'un triangle""" 9 | return (b+h)/2 10 | -------------------------------------------------------------------------------- /067. Calculer l'aire et le périmètre d'un carré/carre.py: -------------------------------------------------------------------------------- 1 | def perimetre_carre(cote): 2 | """Calcule le périmètre d'un carré""" 3 | return cote*4 4 | 5 | 6 | 7 | def aire_carre(cote): 8 | """Calcule l'aire d'un carré""" 9 | 10 | return cote**2 11 | -------------------------------------------------------------------------------- /067. Calculer l'aire et le périmètre d'un carré/test_carre.py: -------------------------------------------------------------------------------- 1 | from carre import * 2 | 3 | #On calcule le périmètre des carrés dont les côtés vont de 1 à 10 4 | for i in range(1, 11): 5 | print("Périmètre : {}".format(perimetre_carre(i))) 6 | 7 | 8 | #On calcule l'aire des carrés dont les côtés vont de 1 à 10 9 | for i in range(1, 11): 10 | print("Aire : {}".format(aire_carre(i))) 11 | -------------------------------------------------------------------------------- /068. Calculer l'aire et le périmètre d'un rectangle/rectangle.py: -------------------------------------------------------------------------------- 1 | def perimetre_rectangle(hauteur, largeur): 2 | """Calcule le périmètre d'un rectangle""" 3 | return 2*hauteur + 2*largeur 4 | 5 | 6 | 7 | def aire_rectangle(hauteur, largeur): 8 | """Calcule l'aire d'un rectangle""" 9 | return hauteur*largeur 10 | -------------------------------------------------------------------------------- /068. Calculer l'aire et le périmètre d'un rectangle/test_rectangle.py: -------------------------------------------------------------------------------- 1 | from rectangle import * 2 | 3 | h, l = 2, 3 4 | print("Périmètre : {}".format(perimetre_rectangle(h, l))) 5 | 6 | h, l = 4, 5 7 | print("Périmètre : {}".format(perimetre_rectangle(h, l))) 8 | 9 | h, l = 2, 6 10 | print("Périmètre : {}".format(perimetre_rectangle(h, l))) 11 | 12 | h, l = 3, 9 13 | print("Périmètre : {}".format(perimetre_rectangle(h, l))) 14 | 15 | h, l = 2, 3 16 | print("Aire : {}".format(aire_rectangle(h, l))) 17 | 18 | h, l = 4, 5 19 | print("Aire : {}".format(aire_rectangle(h, l))) 20 | 21 | h, l = 2, 6 22 | print("Aire : {}".format(aire_rectangle(h, l))) 23 | 24 | h, l = 3, 9 25 | print("Aire : {}".format(aire_rectangle(h, l))) 26 | -------------------------------------------------------------------------------- /069. Vérifier que tous les éléments d'une liste sont différents/liste_difference.py: -------------------------------------------------------------------------------- 1 | def elements_uniques(liste): 2 | """Renvoie True si la liste contient que des éléments uniques, renvoie False sinon""" 3 | 4 | if len(liste) == len(list(set(liste))): 5 | return True 6 | 7 | else: 8 | return False 9 | -------------------------------------------------------------------------------- /069. Vérifier que tous les éléments d'une liste sont différents/test_liste_difference.py: -------------------------------------------------------------------------------- 1 | from liste_difference import * 2 | 3 | liste = [1,2,3,4,5,6] 4 | print(elements_uniques(liste)) 5 | 6 | liste = [1,2,3,4,5,6,2] 7 | print(elements_uniques(liste)) 8 | 9 | liste = ["Sarah", "Antoine", "Maxime"] 10 | print(elements_uniques(liste)) 11 | 12 | liste = ["Sarah", "Antoine", "Maxime", "Antoine"] 13 | print(elements_uniques(liste)) 14 | 15 | liste = [2,2,2,2,2,2,2] 16 | print(elements_uniques(liste)) 17 | -------------------------------------------------------------------------------- /070. Mélanger les caractères d'une chaîne de caractères/shuffle.py: -------------------------------------------------------------------------------- 1 | from random import randint, shuffle 2 | import string_utils 3 | 4 | 5 | def shuffle_string(string): 6 | """Mélange les caractères d'une chaîne de caractères""" 7 | 8 | new_string = "" 9 | while(len(string) > 0): 10 | random_digit = randint(0, len(string)-1) 11 | new_string += string[random_digit] 12 | string = string[:random_digit] + string[random_digit+1:] 13 | 14 | return new_string 15 | 16 | 17 | 18 | def shuffle_string_2(string): 19 | """Mélange les caractères d'une chaîne de caractères avec la méthode shuffle 20 | du module random""" 21 | liste = list(string) 22 | shuffle(liste) 23 | return "".join(liste) 24 | 25 | 26 | 27 | def shuffle_string_utils(string): 28 | """Mélange les caractères d'une chaîne de caractères avec la méthode shuffle 29 | du module string_utils 30 | Ne pas oublier d'installer python-string-utils avec pip""" 31 | 32 | return string_utils.shuffle(string) 33 | -------------------------------------------------------------------------------- /070. Mélanger les caractères d'une chaîne de caractères/test_shuffle.py: -------------------------------------------------------------------------------- 1 | from shuffle import * 2 | 3 | string = "Foxxpy" 4 | print(shuffle_string(string)) 5 | print(shuffle_string_2(string)) 6 | print(shuffle_string_utils(string)) 7 | 8 | print() 9 | string = "Programmation" 10 | print(shuffle_string(string)) 11 | print(shuffle_string_2(string)) 12 | print(shuffle_string_utils(string)) 13 | 14 | print() 15 | string = "Python" 16 | print(shuffle_string(string)) 17 | print(shuffle_string_2(string)) 18 | print(shuffle_string_utils(string)) 19 | 20 | print() 21 | string = "abcdefghijklmnopqrstuvwxyz" 22 | print(shuffle_string(string)) 23 | print(shuffle_string_2(string)) 24 | print(shuffle_string_utils(string)) 25 | -------------------------------------------------------------------------------- /071. Changer les lettres avec accent en lettres sans accent/test_no_accent.py: -------------------------------------------------------------------------------- 1 | from no_accent import no_accent_char, no_accent_word 2 | 3 | #On teste pour les lettres avec accent 4 | for char in ["ç","é", "ê", "ë", "è", "à", "â", "ä", "ï", "î", "ö", "ô", "û", "ù", "ü"]: 5 | print("{} => {}".format(char, no_accent_char(char))) 6 | 7 | #Test avec des mots 8 | string = "Félicitations! Tu as réussi ton examen!" 9 | print(no_accent_word(string)) 10 | 11 | string = "J'ai créé un remède." 12 | print(no_accent_word(string)) 13 | -------------------------------------------------------------------------------- /072. Tester si deux mots sont des anagrammes/anagramme.py: -------------------------------------------------------------------------------- 1 | def anagramme(string1, string2): 2 | """Teste si deux mots sont des anagrammes. Renvoie True si ils sont des anagrammes, 3 | renvoie False sinon""" 4 | 5 | #Si les deux mots n'ont pas la même longueur, on sait d'avance qu'ils ne sont 6 | #pas des anagrammes 7 | if len(string1) != len(string2): 8 | return False 9 | 10 | if sort(string1.upper()) == sort(string2.upper()): 11 | return True 12 | else: 13 | return False 14 | -------------------------------------------------------------------------------- /073. Retirer les ponctuations d'une chaîne de caractères/retirer_ponctuation.py: -------------------------------------------------------------------------------- 1 | def retirer_ponctuation(string): 2 | """Retire les ponctuations d'une chaîne de caractères""" 3 | 4 | if not string.isalpha(): 5 | #On retire tous les caractères avant les majuscule (65) dans la table ascii 6 | for i in range(65): 7 | if chr(i) in string: 8 | string = string.replace(chr(i), "") 9 | 10 | for i in range(91, 97): 11 | if chr(i) in string: 12 | string = string.replace(chr(i), "") 13 | 14 | for i in range(123, 128): 15 | if chr(i) in string: 16 | string = string.replace(chr(i), "") 17 | 18 | for i in range(128, 192): 19 | if chr(i) in string: 20 | string = string.replace(chr(i), "") 21 | 22 | if chr(8217) in string: 23 | string = string.replace(chr(8217), "") 24 | 25 | return string 26 | -------------------------------------------------------------------------------- /073. Retirer les ponctuations d'une chaîne de caractères/test_retirer_ponctuation.py: -------------------------------------------------------------------------------- 1 | from retirer_ponctuation import retirer_ponctuation 2 | 3 | string = "Bonjour à tous! Je vous souhaite la bienvenue dans ma demeure." 4 | print(retirer_ponctuation(string)) 5 | 6 | string = "Ouiiiii!!!! IL A ENFIN RECU SES BILLETS DE TRAIN!!!!!!" 7 | print(retirer_ponctuation(string)) 8 | 9 | string = "!!!!... ||||-*-+ F o !@ x ,,,x ;:;!..\" p []]](]§§§ y????" 10 | print(retirer_ponctuation(string)) 11 | 12 | string = "L'allemand est difficile à apprendre!" 13 | print(retirer_ponctuation(string)) 14 | 15 | string = "Joyeux, ivre, fatigué, le nez qui pique, Clown Hary skie dans l’ombre" 16 | string = "’" 17 | print(ord(string)) 18 | -------------------------------------------------------------------------------- /074. Tester si une chaîne de caractères est un pangramme/no_accent.py: -------------------------------------------------------------------------------- 1 | def no_accent_char(char): 2 | table_correspondance = {192 : 65, 3 | 193 : 65, 4 | 194 : 65, 5 | 195 : 65, 6 | 196 : 65, 7 | 197 : 65, 8 | 198 : 65, 9 | 199 : 67, 10 | 200 : 69, 11 | 201 : 69, 12 | 202 : 69, 13 | 203 : 69, 14 | 204 : 73, 15 | 205 : 73, 16 | 206 : 73, 17 | 207 : 73, 18 | 208 : 68, 19 | 209 : 78, 20 | 210 : 79, 21 | 211 : 79, 22 | 212 : 79, 23 | 213 : 79, 24 | 214 : 79, 25 | 216 : 79, 26 | 217 : 85, 27 | 218 : 85, 28 | 219 : 85, 29 | 220 : 85, 30 | 221 : 89, 31 | 224 : 97, 32 | 225 : 97, 33 | 226 : 97, 34 | 227 : 97, 35 | 228 : 97, 36 | 229 : 97, 37 | 230 : 97, 38 | 231 : 99, 39 | 232 : 101, 40 | 233 : 101, 41 | 234 : 101, 42 | 235 : 101, 43 | 236 : 105, 44 | 237 : 105, 45 | 238 : 105, 46 | 239 : 105, 47 | 240 : 111, 48 | 241 : 110, 49 | 242 : 111, 50 | 243 : 111, 51 | 244 : 111, 52 | 245 : 111, 53 | 246 : 111, 54 | 248 : 111, 55 | 249 : 117, 56 | 250 : 117, 57 | 251 : 117, 58 | 252 : 117, 59 | 253 : 121 60 | 61 | 62 | } 63 | 64 | if 192 <= ord(char) <= 214 or 216 <= ord(char) <= 253: 65 | return chr(table_correspondance[ord(char)]) 66 | else: 67 | return char 68 | 69 | return new_string 70 | 71 | 72 | def no_accent_word(string): 73 | new_string = "" 74 | for char in string: 75 | new_string += no_accent_char(char) 76 | 77 | return new_string 78 | 79 | -------------------------------------------------------------------------------- /074. Tester si une chaîne de caractères est un pangramme/pangramme.py: -------------------------------------------------------------------------------- 1 | from no_accent import no_accent_word 2 | from retirer_ponctuation import retirer_ponctuation 3 | 4 | def pangramme(string): 5 | """Détermine si la chaine de caractères est un pangramme. 6 | Un pangramme est une phrase qui contient toutes les lettres de l'alphabet.""" 7 | 8 | #On retire les accents, les ponctuations et on passe le texte en majuscule 9 | string = retirer_ponctuation(string) 10 | string = no_accent_word(string) 11 | string = string.upper() 12 | 13 | if "œ".upper() in string: 14 | string = string.replace("œ".upper(), "oe".upper()) 15 | 16 | #Si la longueur du set est de 26, c'est qu'on a toutes les lettres de l'alphabet 17 | if len(set(string)) == 26: 18 | return True 19 | else: 20 | return False 21 | -------------------------------------------------------------------------------- /074. Tester si une chaîne de caractères est un pangramme/retirer_ponctuation.py: -------------------------------------------------------------------------------- 1 | def retirer_ponctuation(string): 2 | """Retire les ponctuations d'une chaîne de caractères""" 3 | 4 | if not string.isalpha(): 5 | #On retire tous les caractères avant les majuscule (65) dans la table ascii 6 | for i in range(65): 7 | if chr(i) in string: 8 | string = string.replace(chr(i), "") 9 | 10 | for i in range(91, 97): 11 | if chr(i) in string: 12 | string = string.replace(chr(i), "") 13 | 14 | for i in range(123, 128): 15 | if chr(i) in string: 16 | string = string.replace(chr(i), "") 17 | 18 | for i in range(128, 192): 19 | if chr(i) in string: 20 | string = string.replace(chr(i), "") 21 | 22 | if chr(8217) in string: 23 | string = string.replace(chr(8217), "") 24 | 25 | return string 26 | -------------------------------------------------------------------------------- /075. Afficher les éléments d'une liste absents d'une autre liste/are_in_other_list.py: -------------------------------------------------------------------------------- 1 | def are_in_other_list(liste1, liste2): 2 | """Renvoie une liste des éléments de la première liste qui ne sont pas 3 | présents dans la seconde liste""" 4 | 5 | element_not_in_other_list = list() 6 | for element in liste1: 7 | if not element in liste2: 8 | element_not_in_other_list.append(element) 9 | 10 | return element_not_in_other_list 11 | -------------------------------------------------------------------------------- /075. Afficher les éléments d'une liste absents d'une autre liste/test_are_in_other_list.py: -------------------------------------------------------------------------------- 1 | from are_in_other_list import are_in_other_list 2 | 3 | liste1 = [1,2,3,4] 4 | liste2 = [1,2,3] 5 | print(are_in_other_list(liste1, liste2)) 6 | 7 | print() 8 | liste1 = [x for x in range(100)] 9 | liste2 = [x for x in range(50,101)] 10 | print(are_in_other_list(liste1, liste2)) 11 | 12 | print() 13 | liste1 = ["Bernard", "Antoine", "Fabrice"] 14 | liste2 = ["Antoine", "Fabrice", "Bernard"] 15 | print(are_in_other_list(liste1, liste2)) 16 | 17 | print() 18 | liste1 = ["Bernard", "Antoine", "Fabrice", "John", "Frédéric"] 19 | liste2 = ["Antoine", "Fabrice", "Bernard"] 20 | print(are_in_other_list(liste1, liste2)) 21 | -------------------------------------------------------------------------------- /076. Calculer la distance entre deux points/distance_between_2_points.py: -------------------------------------------------------------------------------- 1 | def distance_between_2_points(x1, x2, y1, y2): 2 | """Calcule la distance entre 2 points""" 3 | 4 | return ((x2 - x1)**2 + (y2 - y1)**2)**0.5 5 | -------------------------------------------------------------------------------- /076. Calculer la distance entre deux points/test_distance_between_2_points.py: -------------------------------------------------------------------------------- 1 | from distance_between_2_points import distance_between_2_points 2 | 3 | x1, x2, y1, y2 = 1, 2, 1, 2 4 | print(distance_between_2_points(x1,x2,y1,y2)) 5 | 6 | x1, x2, y1, y2 = 1, 3, 1, 3 7 | print(distance_between_2_points(x1,x2,y1,y2)) 8 | 9 | x1, x2, y1, y2 = -1, 0, 0, 6 10 | print(distance_between_2_points(x1,x2,y1,y2)) 11 | -------------------------------------------------------------------------------- /077. Calculer l'hypoténuse d'un triangle rectangle/hypotenuse.py: -------------------------------------------------------------------------------- 1 | def hypotenuse(a, b): 2 | """Calcule la valeur de l'hypoténuse d'un triangle rectangle""" 3 | 4 | return (a**2 + b**2)**0.5 5 | -------------------------------------------------------------------------------- /077. Calculer l'hypoténuse d'un triangle rectangle/test_hypotenuse.py: -------------------------------------------------------------------------------- 1 | from hypotenuse import hypotenuse 2 | 3 | a, b = 3, 4 4 | print(hypotenuse(a,b)) 5 | 6 | a, b = 5, 6 7 | print(hypotenuse(a,b)) 8 | 9 | a, b = 1, 2 10 | print(hypotenuse(a,b)) 11 | 12 | a, b = 1, 50 13 | print(hypotenuse(a,b)) 14 | -------------------------------------------------------------------------------- /078. Tester si toutes les valeurs d'un dictionnaire sont égales/same_values.py: -------------------------------------------------------------------------------- 1 | def same_values(dictionnaire): 2 | """Renvoie True si toutes les valeurs d'un dictionnaire sont pareils. False sinon.""" 3 | 4 | value_to_check = None 5 | 6 | for key, value in dictionnaire.items(): 7 | #Si on a pas encore rencontré de valeur, on en affecte une à value_to_check 8 | if value_to_check == None: 9 | value_to_check = value 10 | 11 | #On compare les valeurs avec value_to_check 12 | if value != value_to_check: 13 | return False 14 | 15 | return True 16 | 17 | 18 | 19 | def same_values_set(dictionnaire): 20 | """Renvoie True si toutes les valeurs d'un dictionnaire sont pareils. False sinon.""" 21 | if len(set(dictionnaire.values())) == 1: 22 | return True 23 | else: 24 | return False 25 | -------------------------------------------------------------------------------- /078. Tester si toutes les valeurs d'un dictionnaire sont égales/test_same_values.py: -------------------------------------------------------------------------------- 1 | from same_values import * 2 | 3 | dictionnaire = {"a" : 1, "b" : 1} 4 | print(dictionnaire) 5 | print(same_values(dictionnaire)) 6 | print(same_values_set(dictionnaire)) 7 | print() 8 | 9 | dictionnaire = {"a" : 1, "b" : 2} 10 | print(dictionnaire) 11 | print(same_values(dictionnaire)) 12 | print(same_values_set(dictionnaire)) 13 | print() 14 | 15 | dictionnaire = {"Johnny" : 1000, "Sarah" : 1000} 16 | print(dictionnaire) 17 | print(same_values(dictionnaire)) 18 | print(same_values_set(dictionnaire)) 19 | print() 20 | 21 | dictionnaire = {"Johnny" : 1000, "Sarah" : 1000, "Bernard" : 999} 22 | print(dictionnaire) 23 | print(same_values(dictionnaire)) 24 | print(same_values_set(dictionnaire)) 25 | print() 26 | 27 | dictionnaire = {"a" : 1, "b" : 1, "c" : 1, "d" : "bonjour"} 28 | print(dictionnaire) 29 | print(same_values(dictionnaire)) 30 | print(same_values_set(dictionnaire)) 31 | print() 32 | -------------------------------------------------------------------------------- /079. Tester si une phrase est un heterogramme/test_est_un_heterogramme.py: -------------------------------------------------------------------------------- 1 | from est_un_heterogramme import est_un_heterogramme 2 | 3 | string = "Foxxpy" 4 | print("{} : {}".format(string, est_un_heterogramme(string))) 5 | print() 6 | 7 | string = "Foxpy" 8 | print("{} : {}".format(string, est_un_heterogramme(string))) 9 | print() 10 | 11 | string = "Maths" 12 | print("{} : {}".format(string, est_un_heterogramme(string))) 13 | print() 14 | 15 | string = "Danser" 16 | print("{} : {}".format(string, est_un_heterogramme(string))) 17 | print() 18 | 19 | string = "Félix" 20 | print("{} : {}".format(string, est_un_heterogramme(string))) 21 | print() 22 | 23 | string = "Météo" 24 | print("{} : {}".format(string, est_un_heterogramme(string))) 25 | print() 26 | -------------------------------------------------------------------------------- /080. Tester si une phrase est un isogramme/test_est_un_isogramme.py: -------------------------------------------------------------------------------- 1 | from est_un_isogramme import est_un_isogramme 2 | 3 | print("----- ISOGRAMME -----") 4 | string = "Dodo" 5 | print("{} : {}".format(string, est_un_isogramme(string))) 6 | 7 | string = "Grain" 8 | print("{} : {}".format(string, est_un_isogramme(string))) 9 | 10 | string = "MANGER" 11 | print("{} : {}".format(string, est_un_isogramme(string))) 12 | 13 | string = "MouLinE" 14 | print("{} : {}".format(string, est_un_isogramme(string))) 15 | 16 | string = "DélatION" 17 | print("{} : {}".format(string, est_un_isogramme(string))) 18 | 19 | string = "SaXoNiQuE" 20 | print("{} : {}".format(string, est_un_isogramme(string))) 21 | 22 | string = "complaire" 23 | print("{} : {}".format(string, est_un_isogramme(string))) 24 | 25 | print("\n----- NON ISOGRAMME -----") 26 | 27 | string = "mEnteur" 28 | print("{} : {}".format(string, est_un_isogramme(string))) 29 | 30 | string = "Battre" 31 | print("{} : {}".format(string, est_un_isogramme(string))) 32 | 33 | string = "créé" 34 | print("{} : {}".format(string, est_un_isogramme(string))) 35 | 36 | string = "créée" 37 | print("{} : {}".format(string, est_un_isogramme(string))) 38 | 39 | string = "maîtriser" 40 | print("{} : {}".format(string, est_un_isogramme(string))) 41 | -------------------------------------------------------------------------------- /081. Suite de Conway (Count and say)/countAndSay.py: -------------------------------------------------------------------------------- 1 | def countAndSay(n): 2 | """Donne la n-ème ligne de la suite de Conway""" 3 | 4 | sequence = [1] 5 | 6 | for _ in range(n-1): 7 | suivant = [] 8 | for num in sequence: 9 | if not suivant or suivant[-1] != num: 10 | suivant += [1, num] 11 | else: 12 | suivant[-2] += 1 13 | sequence = suivant 14 | 15 | return "".join(map(str, sequence)) 16 | -------------------------------------------------------------------------------- /081. Suite de Conway (Count and say)/test_countAndSay.py: -------------------------------------------------------------------------------- 1 | from countAndSay import countAndSay 2 | 3 | for n in range(1, 11): 4 | print(countAndSay(n)) 5 | -------------------------------------------------------------------------------- /082. Trier 3 nombres sans utiliser de boucle ni de structure conditionnelle/sort_3_numbers.py: -------------------------------------------------------------------------------- 1 | def sort_3_numbers(x,y,z): 2 | """Méthode qui trie 3 nombres sans structure conditionnelle""" 3 | 4 | a1 = min(x,y,z) 5 | a3 = max(x,y,z) 6 | a2 = x+y+z - a1 - a3 7 | 8 | return [a1,a2,a3] 9 | -------------------------------------------------------------------------------- /082. Trier 3 nombres sans utiliser de boucle ni de structure conditionnelle/test_sort_3_numbers.py: -------------------------------------------------------------------------------- 1 | from sort_3_numbers import sort_3_numbers 2 | 3 | a,b,c = 3,2,1 4 | print(sort_3_numbers(a,b,c)) 5 | 6 | a,b,c = 1,2,3 7 | print(sort_3_numbers(a,b,c)) 8 | 9 | a,b,c = 9, -8, 5 10 | print(sort_3_numbers(a,b,c)) 11 | 12 | a,b,c = -3, -4, -5 13 | print(sort_3_numbers(a,b,c)) 14 | -------------------------------------------------------------------------------- /083. Déterminer l'équation ax+b à partir de 2 points/find_equation_line.py: -------------------------------------------------------------------------------- 1 | def find_equation_line(x1, y1, x2, y2): 2 | """Détermine l'équation de la droite y = ax+b à partir de deux points appartenant 3 | à cette droite""" 4 | 5 | print("Point A : ({},{})".format(x1, y1)) 6 | print("Point B : ({},{})".format(x2, y2)) 7 | 8 | a = (y1 - y2) / (x1 - x2) 9 | b = y2 - a*x2 10 | print("L'équation est {}x+{}".format(a, b)) 11 | 12 | return a, b 13 | 14 | -------------------------------------------------------------------------------- /083. Déterminer l'équation ax+b à partir de 2 points/test_find_equation_line.py: -------------------------------------------------------------------------------- 1 | from find_equation_line import find_equation_line 2 | 3 | x1, y1, x2, y2 = -1, 2, 1.5, -0.25 4 | find_equation_line(x1,y1,x2,y2) 5 | print() 6 | 7 | x1, y1, x2, y2 = -1, -1, 1, 1 8 | find_equation_line(x1,y1,x2,y2) 9 | print() 10 | 11 | x1, y1, x2, y2 = 0, 0, 1, 0 #Droite des abscisse 12 | find_equation_line(x1,y1,x2,y2) 13 | print() 14 | 15 | x1, y1, x2, y2 = -10, -5, 10, 5 16 | find_equation_line(x1,y1,x2,y2) 17 | print() 18 | 19 | x1, y1, x2, y2 = 1, 2, 3, 4 20 | find_equation_line(x1,y1,x2,y2) 21 | print() 22 | -------------------------------------------------------------------------------- /084. Tester si une chaîne de caractères est un palindrome/string_is_palindrome.py: -------------------------------------------------------------------------------- 1 | def string_is_palindrome(string): 2 | """Test si une chaîne de caractères est un palindrome""" 3 | 4 | if len(string) < 1: 5 | return True 6 | else: 7 | if string[0] == string[-1]: 8 | return string_is_palindrome(string[1:-1]) 9 | else: 10 | return False 11 | -------------------------------------------------------------------------------- /084. Tester si une chaîne de caractères est un palindrome/test_string_is_palindrome.py: -------------------------------------------------------------------------------- 1 | from string_is_palindrome import string_is_palindrome 2 | 3 | string = "KAYAK" 4 | print("{} : {}".format(string, string_is_palindrome(string))) 5 | print() 6 | 7 | string = "KayAk" 8 | print("{} : {}".format(string, string_is_palindrome(string))) 9 | print() 10 | 11 | string = "Jean" 12 | print("{} : {}".format(string, string_is_palindrome(string))) 13 | print() 14 | -------------------------------------------------------------------------------- /085. Tester si une phrase est un palindrome/is_palindrome.py: -------------------------------------------------------------------------------- 1 | from no_accent import no_accent_word 2 | from retirer_ponctuation import retirer_ponctuation 3 | 4 | def is_palindrome(phrase): 5 | phrase = phrase.upper() 6 | phrase= no_accent_word(phrase) 7 | phrase = retirer_ponctuation(phrase) 8 | 9 | return phrase == phrase[::-1] 10 | 11 | print(is_palindrome("À révéler mon nom, mon nom relèvera")) 12 | print(is_palindrome("Eh ! ça va, la vache ?")) 13 | print(is_palindrome("L'ami naturel ? Le rut animal.")) 14 | print(is_palindrome("Ta bête te bat.")) 15 | print(is_palindrome("Engage le jeu que je le gagne")) 16 | print(is_palindrome("Noël a trop par rapport à Léon")) 17 | print(is_palindrome("À l'étape, épate-la ! ")) 18 | print(is_palindrome("La mère Gide digère mal")) 19 | print(is_palindrome("Léon, émir cornu, d'un roc rime Noël ")) 20 | print(is_palindrome("Élu par cette crapule")) 21 | print(is_palindrome("Ésope reste ici et se repose")) 22 | print(is_palindrome("Luc notre valet alla te laver ton cul ")) 23 | print(is_palindrome("Tâte l'État ! ")) 24 | print(is_palindrome(" rue Verlaine gela le génial rêveur ")) 25 | print(is_palindrome("Elle dira hélas à la sale haridelle")) 26 | -------------------------------------------------------------------------------- /085. Tester si une phrase est un palindrome/no_accent.py: -------------------------------------------------------------------------------- 1 | def no_accent_char(char): 2 | table_correspondance = {192 : 65, 3 | 193 : 65, 4 | 194 : 65, 5 | 195 : 65, 6 | 196 : 65, 7 | 197 : 65, 8 | 198 : 65, 9 | 199 : 67, 10 | 200 : 69, 11 | 201 : 69, 12 | 202 : 69, 13 | 203 : 69, 14 | 204 : 73, 15 | 205 : 73, 16 | 206 : 73, 17 | 207 : 73, 18 | 208 : 68, 19 | 209 : 78, 20 | 210 : 79, 21 | 211 : 79, 22 | 212 : 79, 23 | 213 : 79, 24 | 214 : 79, 25 | 216 : 79, 26 | 217 : 85, 27 | 218 : 85, 28 | 219 : 85, 29 | 220 : 85, 30 | 221 : 89, 31 | 224 : 97, 32 | 225 : 97, 33 | 226 : 97, 34 | 227 : 97, 35 | 228 : 97, 36 | 229 : 97, 37 | 230 : 97, 38 | 231 : 99, 39 | 232 : 101, 40 | 233 : 101, 41 | 234 : 101, 42 | 235 : 101, 43 | 236 : 105, 44 | 237 : 105, 45 | 238 : 105, 46 | 239 : 105, 47 | 240 : 111, 48 | 241 : 110, 49 | 242 : 111, 50 | 243 : 111, 51 | 244 : 111, 52 | 245 : 111, 53 | 246 : 111, 54 | 248 : 111, 55 | 249 : 117, 56 | 250 : 117, 57 | 251 : 117, 58 | 252 : 117, 59 | 253 : 121 60 | 61 | 62 | } 63 | 64 | if 192 <= ord(char) <= 214 or 216 <= ord(char) <= 253: 65 | return chr(table_correspondance[ord(char)]) 66 | else: 67 | return char 68 | 69 | return new_string 70 | 71 | 72 | def no_accent_word(string): 73 | new_string = "" 74 | for char in string: 75 | new_string += no_accent_char(char) 76 | 77 | return new_string 78 | 79 | -------------------------------------------------------------------------------- /085. Tester si une phrase est un palindrome/palindrome_recursion.py: -------------------------------------------------------------------------------- 1 | #Fonction qui teste si la chaîne de caractères envoyée est un palindrome 2 | #Exemple palindromes : "Un radar nu", "Engage le jeu que je le gagne", "Le ruban à Burel", "Un roc cornu" 3 | 4 | def recursion_palindrome(message, i=0, j=0): 5 | 6 | if i == 0 and j == 0: 7 | j = len(message) - 1 8 | is_palindrome = True 9 | 10 | if j - i > 1: 11 | c = [" ", ",", "-", "'", "!", "?"] 12 | if message[i] in c: 13 | is_palindrome = recursion_palindrome(message, i+1, j) 14 | 15 | elif message[j] in c: 16 | is_palindrome = recursion_palindrome(message, i, j-1) 17 | 18 | elif message[i].lower() != message[j].lower() and j - i > 1: 19 | return False 20 | 21 | else: 22 | is_palindrome = recursion_palindrome(message, i+1, j-1) 23 | 24 | return is_palindrome 25 | 26 | #Exemple avec le palindrome : "Un roc cornu" 27 | #recursion_palindrome("Un roc cornu", i=0, j=0) 28 | # recursion_palindrome("Un roc cornu", i=1, j=10) 29 | # recursion_palindrome("Un roc cornu", i=2, j=9) 30 | # recursion_palindrome("Un roc cornu", i=3, j=9) 31 | # recursion_palindrome("Un roc cornu", i=4, j=8) 32 | # recursion_palindrome("Un roc cornu", i=5, j=7) 33 | # recursion_palindrome("Un roc cornu", i=6, j=6) 34 | # return True 35 | # return True 36 | # return True 37 | # return True 38 | # return True 39 | # return True 40 | #return True 41 | 42 | # --- Palindromes --- 43 | #Eh ! ça va, la vache ? 44 | #La mariee ira mal 45 | #Un port trop nu 46 | #Engage le jeu que je le gagne 47 | #La mere Gide digere mal 48 | #Tu l'as trop ecrase, Cesar, ce Port-Salut 49 | -------------------------------------------------------------------------------- /085. Tester si une phrase est un palindrome/retirer_ponctuation.py: -------------------------------------------------------------------------------- 1 | def retirer_ponctuation(string): 2 | """Retire les ponctuations d'une chaîne de caractères""" 3 | 4 | if not string.isalpha(): 5 | #On retire tous les caractères avant les majuscule (65) dans la table ascii 6 | for i in range(65): 7 | if chr(i) in string: 8 | string = string.replace(chr(i), "") 9 | 10 | for i in range(91, 97): 11 | if chr(i) in string: 12 | string = string.replace(chr(i), "") 13 | 14 | for i in range(123, 128): 15 | if chr(i) in string: 16 | string = string.replace(chr(i), "") 17 | 18 | for i in range(128, 192): 19 | if chr(i) in string: 20 | string = string.replace(chr(i), "") 21 | 22 | if chr(8217) in string: 23 | string = string.replace(chr(8217), "") 24 | 25 | return string 26 | -------------------------------------------------------------------------------- /086. Somme des colonnes et des lignes d'une matrice/sum_matrix.py: -------------------------------------------------------------------------------- 1 | def sum_matrix(matrix, column=False): 2 | if not column: 3 | matrix_line = [] 4 | for line in matrix: 5 | matrix_line.append(sum(line)) 6 | return matrix_line 7 | 8 | else: 9 | matrix_column = [] 10 | M = len(matrix) 11 | N = len(matrix[0]) 12 | for i in range(N): 13 | total = 0 14 | for j in range(M): 15 | total += matrix[j][i] 16 | matrix_column.append(total) 17 | return matrix_column 18 | -------------------------------------------------------------------------------- /086. Somme des colonnes et des lignes d'une matrice/test_sum_matrix.py: -------------------------------------------------------------------------------- 1 | from sum_matrix import sum_matrix 2 | 3 | matrix = [[1,1,1],[2,2,2]] 4 | print(sum_matrix(matrix, True)) 5 | print(sum_matrix(matrix, False)) 6 | 7 | matrix = [[1,1,1],[1,1,1], [1,1,1]] 8 | print(sum_matrix(matrix, True)) 9 | print(sum_matrix(matrix, False)) 10 | 11 | matrix = [[0,0], [4,4]] 12 | print(sum_matrix(matrix, True)) 13 | print(sum_matrix(matrix, False)) 14 | -------------------------------------------------------------------------------- /087. Trouver les sunny numbers dans un intervalle/sunny.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | def sunny(n): 4 | """Un sunny number est un nombre qui a une racine carrée parfaite quand on 5 | lui ajoute 1""" 6 | 7 | x = sqrt(n+1) 8 | return int(x) == x 9 | 10 | 11 | 12 | def sunny_interval(inf, sup): 13 | """Cherche tous les sunny numbers dans un intervalle [inf, sup]""" 14 | 15 | sunny_numbers = list() 16 | for i in range(inf, sup+1): 17 | if sunny(i): 18 | print("{} est un sunny number".format(i)) 19 | sunny_numbers.append(i) 20 | return sunny_numbers 21 | -------------------------------------------------------------------------------- /087. Trouver les sunny numbers dans un intervalle/test_sunny.py: -------------------------------------------------------------------------------- 1 | from sunny import sunny, sunny_interval 2 | 3 | sunny_interval(1,1001) 4 | -------------------------------------------------------------------------------- /088. Calculer la valeur du nombre d'Euler e/euler.py: -------------------------------------------------------------------------------- 1 | #Codée à l'épisode 22 2 | def factorial(nb): 3 | """Calcul nb!""" 4 | product = 1 5 | for num in range(1, nb+1): 6 | product *= num 7 | 8 | return product 9 | 10 | def euler(n): 11 | euler_number = 0 12 | for i in range(n): 13 | euler_number += 1/factorial(i) 14 | return euler_number 15 | -------------------------------------------------------------------------------- /088. Calculer la valeur du nombre d'Euler e/test_euler.py: -------------------------------------------------------------------------------- 1 | from euler import euler 2 | 3 | print(euler(30)) 4 | print(euler(50)) 5 | print(euler(100)) 6 | -------------------------------------------------------------------------------- /089. Trouver les nombres heureux dans un intervalle/happy_numbers.py: -------------------------------------------------------------------------------- 1 | def happy(n): 2 | """Teste le nombre n est un nombre heureux ou non.""" 3 | if n<10: 4 | n = n**2 5 | 6 | #Tant que l'addition des carrés n'a pas atteint un seul chiffre, on continue 7 | while n > 9: 8 | total = 0 9 | for digit in str(n): 10 | total += int(digit)**2 11 | n = total 12 | 13 | return n == 1 14 | -------------------------------------------------------------------------------- /089. Trouver les nombres heureux dans un intervalle/test_happy_numbers.py: -------------------------------------------------------------------------------- 1 | from happy_numbers import happy 2 | 3 | for i in range(1000): 4 | if happy(i): 5 | print("{} est un nombre heureux".format(i)) 6 | -------------------------------------------------------------------------------- /090. Trouver les spy numbers dans un intervalle/spy_numbers.py: -------------------------------------------------------------------------------- 1 | from math import prod 2 | 3 | def spy_numbers(n): 4 | """Teste si un nombre est un nombre espion ou non. 5 | Un nombre espion est un nombre dont le produit de ses chiffres est égal 6 | à la somme de ses chiffres""" 7 | 8 | sum_n = sum(map(int, list(str(n)))) 9 | product_n = prod(map(int, list(str(n)))) 10 | return sum_n == product_n 11 | -------------------------------------------------------------------------------- /090. Trouver les spy numbers dans un intervalle/test_spy_numbers.py: -------------------------------------------------------------------------------- 1 | from spy_numbers import spy_numbers 2 | 3 | for i in range(1000): 4 | if spy_numbers(i): 5 | print("{} est un nombre espion".format(i)) 6 | -------------------------------------------------------------------------------- /091. Taux de croissance/croissance.py: -------------------------------------------------------------------------------- 1 | def croissance(valeur, pourcentage, n=1, entier=True): 2 | """Calcul les intérets en appliquant n fois le pourcentage""" 3 | 4 | interet = 0 5 | if entier: 6 | interet = valeur * (1+ (pourcentage/100))**n 7 | else: 8 | interet = valeur * (1 + pourcentage)**n 9 | 10 | return interet 11 | -------------------------------------------------------------------------------- /091. Taux de croissance/test_croissance.py: -------------------------------------------------------------------------------- 1 | from croissance import croissance 2 | 3 | valeur = 100 4 | print(croissance(valeur, 5, 2)) 5 | -------------------------------------------------------------------------------- /092. Série des nombres triangulaires/test_triangulaire.py: -------------------------------------------------------------------------------- 1 | from triangulaire import triangulaire, recursion_triangulaire 2 | 3 | for i in range(1,11): 4 | print(triangulaire(i)) 5 | 6 | print() 7 | for i in range(1,11): 8 | print(recursion_triangulaire(i)) 9 | -------------------------------------------------------------------------------- /092. Série des nombres triangulaires/triangulaire.py: -------------------------------------------------------------------------------- 1 | def triangulaire(n): 2 | """Renvoie le n-ème nombre triangulaire""" 3 | total = 0 4 | for i in range(1, n+1): 5 | total += i 6 | return total 7 | 8 | def recursion_triangulaire(n, i=1): 9 | """Renvoie le n-ème nombre triangulaire""" 10 | total = i 11 | if n > 1: 12 | total += recursion_triangulaire(n-1, i+1) 13 | 14 | return total 15 | 16 | -------------------------------------------------------------------------------- /093. Calculer la distance Euclidienne/euclidean.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | def distance_euclidienne(pt1, pt2): 4 | """Calcule la distance euclidienne entre deux points pour n'importe quelle dimension""" 5 | 6 | if len(pt1) != len(pt2): 7 | return None 8 | 9 | pt_zip = zip(pt1, pt2) 10 | pt_sum_difference = [(x[0] - x[1])**2 for x in pt_zip] 11 | pt_sum = sum(pt_sum_difference) 12 | distance = sqrt(pt_sum) 13 | return distance 14 | -------------------------------------------------------------------------------- /093. Calculer la distance Euclidienne/test_euclidean.py: -------------------------------------------------------------------------------- 1 | from euclidean import distance_euclidienne 2 | 3 | pt1 = (0,0) 4 | pt2 = (1,1) 5 | print(distance_euclidienne(pt1, pt2)) 6 | print() 7 | 8 | #Deux points de même coordonnée 9 | pt1 = (35,35) 10 | pt2 = (35,35) 11 | print(distance_euclidienne(pt1, pt2)) 12 | print() 13 | 14 | #Deux points de même coordonnée : dimension 4 15 | pt1 = (35,35,1,2) 16 | pt2 = (35,35,1,2) 17 | print(distance_euclidienne(pt1, pt2)) 18 | print() 19 | 20 | pt1 = (0,0,0) 21 | pt2 = (2,2,2) 22 | print(distance_euclidienne(pt1, pt2)) 23 | print() 24 | -------------------------------------------------------------------------------- /094. Déterminer si un nombre est pair ou impair/pair.py: -------------------------------------------------------------------------------- 1 | def pair(n): 2 | """Renvoie True si le nombre est pair, False si il est impair""" 3 | if n % 2 == 0: 4 | return True 5 | else: 6 | return False 7 | -------------------------------------------------------------------------------- /095. Faire la somme de nombres binaires/somme_binaire.py: -------------------------------------------------------------------------------- 1 | def somme_binaire(binaire1, binaire2): 2 | """Renvoie la somme de deux nombres binaires dans une chaîne de caractères""" 3 | if "0b" in binaire1: 4 | binaire1 = binaire1.replace("0b", "") 5 | 6 | if "0b" in binaire2: 7 | binaire2 = binaire2.replace("0b", "") 8 | 9 | somme = int(binaire1, 2) + int(binaire2, 2) 10 | 11 | return bin(somme) 12 | -------------------------------------------------------------------------------- /095. Faire la somme de nombres binaires/test_somme_binaire.py: -------------------------------------------------------------------------------- 1 | from somme_binaire import somme_binaire 2 | 3 | bin1 = bin(1) 4 | bin2 = bin(7) 5 | print(somme_binaire(bin1,bin2)) 6 | print() 7 | 8 | bin1 = "001000" 9 | bin2 = "0100" 10 | print(somme_binaire(bin1,bin2)) 11 | print() 12 | 13 | bin1 = bin(100) 14 | bin2 = bin(155) 15 | print(somme_binaire(bin1,bin2)) 16 | print() 17 | -------------------------------------------------------------------------------- /096. Rendu de monnaie/__pycache__/monnaie.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/foxxpy/Algorithmie/098b9f339400ca642b698d53df953ceb1fa9fe67/096. Rendu de monnaie/__pycache__/monnaie.cpython-39.pyc -------------------------------------------------------------------------------- /096. Rendu de monnaie/monnaie.py: -------------------------------------------------------------------------------- 1 | def monnaie(prix, paiement): 2 | """Calcul le rendu de monnaie quand le paiement du client est plus élevé 3 | que le prix d'achat""" 4 | 5 | if prix >= paiement: 6 | return 0 7 | 8 | rendu = {} 9 | difference = paiement - prix 10 | fiduciaire = [500, 200, 100, 50, 20, 10, 5, 2, 1, 0.50, 0.2, 0.1, 0.05, 0.02, 0.01] 11 | 12 | for m in fiduciaire: 13 | if difference // m > 0: 14 | rendu[m] = difference // m 15 | difference = difference % m 16 | 17 | return rendu 18 | 19 | 20 | 21 | def calcul_montant_rendu(rendu): 22 | """Calcul le montant rendu en fonction de la monnaie utilisée""" 23 | 24 | total = 0 25 | for key, value in rendu.items(): 26 | total += key*value 27 | return total 28 | -------------------------------------------------------------------------------- /096. Rendu de monnaie/test_monnaie.py: -------------------------------------------------------------------------------- 1 | from monnaie import monnaie, calcul_montant_rendu, diram 2 | 3 | prix = 100.50 4 | paiement = 120.00 5 | print(monnaie(prix,paiement)) 6 | print("Monnaie rendu : {}".format(calcul_montant_rendu(monnaie(prix,paiement)))) 7 | print() 8 | 9 | #Le client a payé le montant exact 10 | prix = 120.00 11 | paiement = 120.00 12 | print(monnaie(prix,paiement)) 13 | print() 14 | 15 | #Le client n'a pas assez d'argent 16 | prix = 150 17 | paiement = 140 18 | print(monnaie(prix,paiement)) 19 | print() 20 | 21 | prix = 2010.50 22 | paiement = 3000 23 | print(monnaie(prix,paiement)) 24 | print("Monnaie rendu : {}".format(calcul_montant_rendu(monnaie(prix,paiement)))) 25 | print() 26 | -------------------------------------------------------------------------------- /097. Réinitialiser un objet Python sans le détruire/reset.py: -------------------------------------------------------------------------------- 1 | def reset(var): 2 | """Réinitialise un objet sans le détruire""" 3 | return type(var)() 4 | -------------------------------------------------------------------------------- /097. Réinitialiser un objet Python sans le détruire/test_reset.py: -------------------------------------------------------------------------------- 1 | from reset import reset 2 | 3 | #Nombre entier 4 | a = 12 5 | print(reset(a)) 6 | 7 | #Float 8 | a = 1.38 9 | print(reset(a)) 10 | 11 | #Chaîne de caractères 12 | a = "Foxxpy" 13 | print(reset(a)) 14 | 15 | #Liste 16 | a = [1,2,3,4,5,6] 17 | print(reset(a)) 18 | 19 | #Dictionnaire 20 | a = {"a" : 1, "b" : 2} 21 | print(reset(a)) 22 | -------------------------------------------------------------------------------- /098. Les nombres strobogrammatiques/Définition.txt: -------------------------------------------------------------------------------- 1 | http://villemin.gerard.free.fr/aNombre/MOTIF/Strobogr.htm 2 | 3 | Nombres qui se lisent aussi bien même si la tablette (l'ardoise) est tenue à l'envers. Autrement-dit: c'est le même nombre après une rotation de 180°. -------------------------------------------------------------------------------- /098. Les nombres strobogrammatiques/est_strobogrammatique.py: -------------------------------------------------------------------------------- 1 | def est_strobogrammatique(n): 2 | """Un nombre strobogrammatique est un nombre qui se lit toujours de la même façon 3 | après avoir pivoté de 180 degrés.""" 4 | strobo = {"0" : "0", "1" : "1", "8" : "8", "6" : "9", "9" : "6"} 5 | 6 | #Si n est un entier, on le caste en chaîne de caractères 7 | if type(n) is int: 8 | n = str(n) 9 | 10 | left = 0 11 | right = len(n) - 1 12 | 13 | while right - left >= 0: 14 | if not n[left] in strobo.keys() or not n[right] in strobo.keys() or n[left] != strobo[n[right]]: 15 | return False 16 | right -= 1 17 | left += 1 18 | 19 | return True 20 | -------------------------------------------------------------------------------- /098. Les nombres strobogrammatiques/test_est_strobogrammatique.py: -------------------------------------------------------------------------------- 1 | from est_strobogrammatique import est_strobogrammatique 2 | 3 | nombre = 101 4 | print(est_strobogrammatique(nombre)) 5 | print() 6 | 7 | nombre = 609 8 | print(est_strobogrammatique(nombre)) 9 | print() 10 | 11 | nombre = 10001 12 | print(est_strobogrammatique(nombre)) 13 | print() 14 | 15 | nombre = 66099 16 | print(est_strobogrammatique(nombre)) 17 | print() 18 | 19 | nombre = 619 20 | print(est_strobogrammatique(nombre)) 21 | print() 22 | 23 | nombre = 629 24 | print(est_strobogrammatique(nombre)) 25 | print() 26 | -------------------------------------------------------------------------------- /099. Evil numbers/evil.py: -------------------------------------------------------------------------------- 1 | def is_evil(n): 2 | """Un evil number, c'est un nombre dont l'écriture binaire possède un nombre 3 | pair de 1""" 4 | 5 | count = 0 6 | #On applique la méthodologie qui permet de convertir un nombre entier en binaire 7 | while n != 0: 8 | if (n%2 == 1): 9 | count += 1 10 | n = n //2 11 | 12 | if count % 2 == 0: 13 | return True 14 | else: 15 | return False 16 | 17 | 18 | 19 | def is_evil_bin(n): 20 | """Un evil number, c'est un nombre dont l'écriture binaire possède un nombre 21 | pair de 1""" 22 | 23 | n = bin(n).replace("0b", "") 24 | if n.count("1") % 2 == 0: 25 | return True 26 | else: 27 | return False 28 | -------------------------------------------------------------------------------- /099. Evil numbers/test_evil.py: -------------------------------------------------------------------------------- 1 | from evil import is_evil, is_evil_bin 2 | 3 | for i in range(0,101): 4 | print("{} : {}".format(i, is_evil(i))) 5 | print("{} : {}".format(i, is_evil_bin(i))) 6 | print() 7 | -------------------------------------------------------------------------------- /100. Disarium numbers/Définition.txt: -------------------------------------------------------------------------------- 1 | Given a number “n”, find if it is Disarium or not. A number is called Disarium if sum of its digits powered with their respective positions is equal to the number itself -------------------------------------------------------------------------------- /100. Disarium numbers/disarium.py: -------------------------------------------------------------------------------- 1 | def disarium(n): 2 | 3 | total = 0 4 | for i, digit in enumerate(str(n)): 5 | total += int(digit)**(i+1) 6 | 7 | return total == n 8 | -------------------------------------------------------------------------------- /100. Disarium numbers/test_disarium.py: -------------------------------------------------------------------------------- 1 | from disarium import disarium 2 | 3 | for i in range(1000): 4 | if disarium(i): 5 | print("{}".format(i)) 6 | -------------------------------------------------------------------------------- /101. Trimorphic numbers/Définition.txt: -------------------------------------------------------------------------------- 1 | Given a number N, the task is to check whether the number is Trimorphic number or not. 2 | A number is called Trimorphic number if and only if its cube ends in the same digits as the number itself. In other words, number appears at the end of its cube. -------------------------------------------------------------------------------- /101. Trimorphic numbers/test_trimorphic.py: -------------------------------------------------------------------------------- 1 | from trimorphic import trimorphic 2 | 3 | for n in range(100): 4 | if trimorphic(n): 5 | print("{} : {}".format(n, n**3)) 6 | -------------------------------------------------------------------------------- /101. Trimorphic numbers/trimorphic.py: -------------------------------------------------------------------------------- 1 | def trimorphic(n): 2 | """Un nombre trimorphique est un nombre dont le cube se termine par les mêmes 3 | chiffres que le nombre qui a été calculé au cube""" 4 | 5 | len_n = len(str(n)) 6 | 7 | #i représente la longueur de n (len_n ci-dessus) 8 | #Si les i derniers caractères de n**3 sont égaux à n, alors n est trimorphic 9 | if str(n**3)[-len_n:] == str(n): 10 | return True 11 | else: 12 | return False 13 | -------------------------------------------------------------------------------- /102. Ugly Number/test_ugly.py: -------------------------------------------------------------------------------- 1 | from ugly import ugly, ugly_interval 2 | 3 | print(ugly_interval(1,100)) 4 | print() 5 | 6 | print(ugly_interval(1,1000)) 7 | print() 8 | -------------------------------------------------------------------------------- /102. Ugly Number/ugly.py: -------------------------------------------------------------------------------- 1 | def ugly(n): 2 | if n <= 0: 3 | return False 4 | 5 | #Tant que n est divisible par 2, on le divise par 2 6 | while n % 2 == 0: 7 | n //= 2 8 | 9 | #Tant que n est divisible par 3, on le divise par 3 10 | while n % 3 ==0: 11 | n //= 3 12 | 13 | #Tant que n est divisible par 5, on le divise par 5 14 | while n % 5 == 0: 15 | n //=5 16 | 17 | return n == 1 18 | 19 | 20 | 21 | def ugly_interval(inf, sup): 22 | """Donne tous les ugly numbers dans un intervalle [inf, sup]""" 23 | 24 | list_ugly_numbers = [] 25 | for i in range(inf, sup+1): 26 | if ugly(i): 27 | list_ugly_numbers.append(i) 28 | return list_ugly_numbers 29 | 30 | print(ugly_interval(1,100)) 31 | -------------------------------------------------------------------------------- /103. Instancier une matrice remplie de zéros/matrice_nulle.py: -------------------------------------------------------------------------------- 1 | def matrice_nulle(M, N): 2 | """Instancie une matrice nulle avec M lignes et N colonnes 3 | Ici, une matrice est une liste de listes""" 4 | 5 | matrice = [] 6 | for i in range(M): 7 | matrice.append([0 for x in range(N)]) 8 | return matrice 9 | -------------------------------------------------------------------------------- /103. Instancier une matrice remplie de zéros/test_matrice_nulle.py: -------------------------------------------------------------------------------- 1 | from matrice_nulle import matrice_nulle 2 | 3 | print(matrice_nulle(3,2)) 4 | print() 5 | 6 | print(matrice_nulle(1,1)) 7 | print() 8 | 9 | print(matrice_nulle(5,5)) 10 | print() 11 | -------------------------------------------------------------------------------- /104. Convertir des nombres entiers en chiffres romains/entier_vers_romain.py: -------------------------------------------------------------------------------- 1 | def entier_vers_romain(n): 2 | int_rom = [(1000, "M"), 3 | (900, "CM"), 4 | (500, "D"), 5 | (400, "CD"), 6 | (100, "C"), 7 | (90, "XC"), 8 | (50, "L"), 9 | (40, "XL"), 10 | (10, "X"), 11 | (9, "IX"), 12 | (5, "V"), 13 | (4, "IV"), 14 | (1, "I")] 15 | 16 | romain = [] 17 | 18 | for i, num in int_rom: 19 | while n >= i: 20 | n -= i 21 | print(n) 22 | romain.append(num) 23 | 24 | return "".join(romain) 25 | 26 | print(entier_vers_romain(10)) 27 | -------------------------------------------------------------------------------- /104. Convertir des nombres entiers en chiffres romains/test_entier_vers_romain.py: -------------------------------------------------------------------------------- 1 | from entier_vers_romain import entier_vers_romain 2 | 3 | #Les 1000 premiers nombres romains 4 | for i in range(1,1001): 5 | print(entier_vers_romain(i)) 6 | -------------------------------------------------------------------------------- /105. Convertir des chiffres romains en nombres entiers/romain_vers_entier.py: -------------------------------------------------------------------------------- 1 | def romain_vers_entier(romain): 2 | """Convertit un nombre romain en nombre entier 3 | Leetcode 13""" 4 | 5 | double = {"CM" : 900, "CD" : 400, "XC" : 90, "XL" : 40, "IX" : 9, "IV" : 4} 6 | unique = {"M" : 1000, "D" : 500, "C" : 100, "L" : 50, "X" : 10, "V" : 5, "I" : 1} 7 | 8 | entier = 0 9 | i = 0 10 | 11 | #Tant qu'on a pas parcouru le nombre romain en entier 12 | while i < len(romain): 13 | if i < len(romain) - 1 and romain[i:i+2] in double: 14 | entier += double[romain[i:i+2]] 15 | i += 2 16 | else: 17 | entier += unique[romain[i]] 18 | i += 1 19 | return entier 20 | -------------------------------------------------------------------------------- /105. Convertir des chiffres romains en nombres entiers/test_romain_vers_entier.py: -------------------------------------------------------------------------------- 1 | from romain_vers_entier import romain_vers_entier 2 | from entier_vers_romain import entier_vers_romain 3 | 4 | #Pour tester notre méthode romain_vers_entier, on convertit d'abord des entiers en romain 5 | #Puis on vérifie si notre méthode réussit à les reconvertir en nombre entier 6 | 7 | romain = [] 8 | for i in range(1,101): 9 | romain.append(entier_vers_romain(i)) 10 | 11 | for i in range(1010,1199): 12 | romain.append(entier_vers_romain(i)) 13 | 14 | for rom in romain: 15 | print(romain_vers_entier(rom)) 16 | 17 | -------------------------------------------------------------------------------- /106. Poids de Hamming/poids_hamming.py: -------------------------------------------------------------------------------- 1 | def poids_hamming(binaire): 2 | """Renvoie le nombre de 1 contenu dans un nombre binaire.""" 3 | 4 | return binaire.count("1") 5 | 6 | 7 | 8 | def poids_hamming_leetcode(binaire): 9 | """Renvoie le nombre de 1 contenu dans un nombre binaire. Leetcode : 191""" 10 | 11 | return sum(bit == "1" for bit in binaire[2:]) 12 | -------------------------------------------------------------------------------- /106. Poids de Hamming/test_poids_hamming.py: -------------------------------------------------------------------------------- 1 | from poids_hamming import poids_hamming, poids_hamming_leetcode 2 | 3 | for i in range(1,100): 4 | print(poids_hamming(bin(i))) 5 | print(poids_hamming_leetcode(bin(i))) 6 | print() 7 | -------------------------------------------------------------------------------- /107. Distance de Hamming/distance_hamming.py: -------------------------------------------------------------------------------- 1 | def distance_hamming(binaire1, binaire2): 2 | """Nombre de bits différents entre deux nombres binaires""" 3 | 4 | #Si les deux nombres binaires ne sont pas de mêmes longueurs, on lève une 5 | #assertionError 6 | assert len(binaire1) == len(binaire2) 7 | 8 | #Si 0b est dans binaire1 ou binaire2, on le retire 9 | if "0b" in binaire1: 10 | binaire1 = binaire1.replace("0b", "") 11 | 12 | if "0b" in binaire2: 13 | binaire2 = binaire2.replace("0b", "") 14 | 15 | distance = 0 16 | for i in range(0, len(binaire1)): 17 | if binaire1[i] != binaire2[i]: 18 | distance +=1 19 | 20 | return distance 21 | -------------------------------------------------------------------------------- /107. Distance de Hamming/test_distance_hamming.py: -------------------------------------------------------------------------------- 1 | from distance_hamming import distance_hamming 2 | 3 | print(distance_hamming("10", "11")) 4 | print(distance_hamming("100", "111")) 5 | print(distance_hamming("10000", "11111")) 6 | print(distance_hamming("100", "101")) 7 | print(distance_hamming("110", "111")) 8 | print(distance_hamming("10000", "10101")) 9 | -------------------------------------------------------------------------------- /108. Jeu de Nim/gagneNim.py: -------------------------------------------------------------------------------- 1 | def gagneNim(baton): 2 | """Détermine si un joueur peut gagner le jeu de Nim suivant le nombre de bâtons 3 | restants.""" 4 | 5 | return baton % 4 != 0 6 | -------------------------------------------------------------------------------- /109. Strong Number/factorial.py: -------------------------------------------------------------------------------- 1 | def factorial(nb): 2 | """Calcul nb!""" 3 | product = 1 4 | for num in range(1, nb+1): 5 | product *= num 6 | 7 | return product 8 | 9 | def recursion_factorial(nb): 10 | """Calcul nb! avec une récursion""" 11 | if nb==1: 12 | return 1 13 | return nb*recursion_factorial(nb-1) 14 | -------------------------------------------------------------------------------- /109. Strong Number/strong_number.py: -------------------------------------------------------------------------------- 1 | from factorial import factorial 2 | 3 | def strong_number(n): 4 | """Détermine si n est un strong number ou non. 5 | Strong number : nombre dont la somme des valeurs factorielles de ses chiffres 6 | est égale à ce nombre""" 7 | 8 | total = 0 9 | for chiffre in str(n): 10 | total += factorial(int(chiffre)) 11 | 12 | return total == n 13 | 14 | 15 | -------------------------------------------------------------------------------- /109. Strong Number/test_strong_number.py: -------------------------------------------------------------------------------- 1 | from strong_number import strong_number 2 | 3 | for i in range(1,1001): 4 | if strong_number(i): 5 | print("{} est un strong number".format(i)) 6 | -------------------------------------------------------------------------------- /110. Armstrong Number/armstrong.py: -------------------------------------------------------------------------------- 1 | def armstrong(n): 2 | """Détermine si n est un armstrong number ou non. 3 | Un armstrong number, c'est un nombre qui est égal à la somme du cube des chiffres 4 | qui le composent""" 5 | 6 | 7 | total = 0 8 | for chiffre in str(n): 9 | total += int(chiffre)**3 10 | 11 | return n == total 12 | -------------------------------------------------------------------------------- /110. Armstrong Number/test_armstrong.py: -------------------------------------------------------------------------------- 1 | from armstrong import armstrong 2 | 3 | for i in range(1,1001): 4 | if armstrong(i): 5 | print("{} est un nombre de armstrong".format(i)) 6 | -------------------------------------------------------------------------------- /111. Super digit/super_digit.py: -------------------------------------------------------------------------------- 1 | def super_digit(n): 2 | while len(str(n)) > 1: 3 | total = 0 4 | for digit in str(n): 5 | total += int(digit) 6 | n = total 7 | return n 8 | -------------------------------------------------------------------------------- /111. Super digit/test_super_digit.py: -------------------------------------------------------------------------------- 1 | from super_digit import super_digit 2 | 3 | #On calcule les super digits des 1000 premiers nombres 4 | for i in range(1, 1001): 5 | print("{} => {}".format(i, super_digit(i))) 6 | -------------------------------------------------------------------------------- /112. Triangle de Floyd/test_triangle_floyd.py: -------------------------------------------------------------------------------- 1 | from triangle_floyd import triangle_floyd 2 | 3 | #On affiche les 10 premiers triangles de Floyd 4 | for i in range(1,11): 5 | print("---") 6 | print(i) 7 | print("---") 8 | triangle_floyd(i) 9 | -------------------------------------------------------------------------------- /112. Triangle de Floyd/triangle_floyd.py: -------------------------------------------------------------------------------- 1 | def triangle_floyd(n): 2 | """Affiche les n premières lignes du triangle de Floyd""" 3 | 4 | nombre = 1 5 | for ligne in range(1, n+1): 6 | for _ in range(nombre_par_ligne): 7 | print(nombre, end=" ") 8 | nombre += 1 9 | print() 10 | 11 | 12 | -------------------------------------------------------------------------------- /113. Fascinating number/fascinating.py: -------------------------------------------------------------------------------- 1 | def is_fascinating(n): 2 | """Un nombre fascinant est un nombre auquel on concatene son multiple de 2 3 | et son multiple de 3. Si le nombre obtenu contient tous les chiffres de 1 4 | à 9, alors c'est un nombre fascinant.""" 5 | 6 | #Si il y'a moins 3 chiffres 7 | if len(str(n)) < 3: 8 | return None 9 | 10 | #On concatène n, n*2 et n*3 11 | num = n 12 | num = int(str(num) + str(n*2)) 13 | num = int(str(num) + str(n*3)) 14 | 15 | #On cherche si tous les chiffres sont présents dans num 16 | liste_chiffres = ["1","2","3","4","5","6","7","8","9"] 17 | for chiffre in str(num): 18 | if chiffre in liste_chiffres: 19 | liste_chiffres.remove(chiffre) 20 | if len(liste_chiffres) == 0: 21 | break 22 | 23 | #Si il ne reste plus de chiffres dans liste_chiffres, c'est qu'ils étaient tous dans num 24 | if len(liste_chiffres) == 0: 25 | return True 26 | else: 27 | return False 28 | 29 | -------------------------------------------------------------------------------- /113. Fascinating number/test_fascinating.py: -------------------------------------------------------------------------------- 1 | from fascinating import is_fascinating 2 | 3 | for i in range(1, 1001): 4 | if is_fascinating(i): 5 | print("{} est un fascinating number.".format(i)) 6 | -------------------------------------------------------------------------------- /114. Nombre automorphe/114. Vignette Nombre automorphe.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/foxxpy/Algorithmie/098b9f339400ca642b698d53df953ceb1fa9fe67/114. Nombre automorphe/114. Vignette Nombre automorphe.jpg -------------------------------------------------------------------------------- /114. Nombre automorphe/test_automorphe.py: -------------------------------------------------------------------------------- 1 | from automorphe import automorphe 2 | 3 | for i in range(1,100): 4 | if automorphe(i): 5 | print("{} est un nombre automorphe".format(i)) 6 | -------------------------------------------------------------------------------- /115. Tester si une grille de sudoku est valide/sudoku_est_valide.py: -------------------------------------------------------------------------------- 1 | def sudoku_est_valide(grille): 2 | 3 | #Test des lignes 4 | for line in grille: 5 | if not len(set(line)) == 9: 6 | return False 7 | 8 | #Test des colonnes 9 | for i in range(9): 10 | column = [] 11 | for j in range(9): 12 | column.append(grille[j][i]) 13 | if not len(set(column)) == 9: 14 | return False 15 | 16 | x0 = (x//3) * 3 17 | y0 = (y//3) * 3 18 | #On détermine si le nombre est valide dans sa sous-grille 3x3 19 | for i in range(0,3): 20 | for j in range(0,3): 21 | if grid[y0+i][x0+j] == n: 22 | return False 23 | return True 24 | 25 | -------------------------------------------------------------------------------- /115. Tester si une grille de sudoku est valide/test_sudoku_est_valide.py: -------------------------------------------------------------------------------- 1 | from sudoku_est_valide import sudoku_est_valide 2 | 3 | grille_valide = [ 4 | [1, 2, 3, 4, 5, 6, 7, 8, 9], 5 | [4, 5, 6, 7, 8, 9, 1, 2, 3], 6 | [7, 8, 9, 1, 2, 3, 4, 5, 6], 7 | [9, 1, 2, 3, 4, 5, 6, 7, 8], 8 | [3, 4, 5, 6, 7, 8, 9, 1, 2], 9 | [6, 7, 8, 9, 1, 2, 3, 4, 5], 10 | [8, 9, 1, 2, 3, 4, 5, 6, 7], 11 | [2, 3, 4, 5, 6, 7, 8, 9, 1], 12 | [5, 6, 7, 8, 9, 1, 2, 3, 4]] 13 | 14 | grille_non_valide = [ 15 | [4, 3, 5, 2, 6, 9, 7, 8, 1], 16 | [6, 8, 2, 5, 7, 1, 4, 9, 3], 17 | [1, 9, 7, 8, 3, 4, 5, 6, 2], 18 | [8, 2, 6, 1, 9, 5, 3, 4, 7], 19 | [3, 7, 4, 6, 8, 2, 9, 1, 5], 20 | [1, 5, 9, 7, 4, 3, 6, 2, 8], 21 | [5, 1, 9, 3, 2, 6, 8, 7, 4], 22 | [2, 4, 8, 9, 5, 7, 1, 3, 6], 23 | [7, 6, 3, 4, 1, 8, 2, 5, 9] 24 | ] 25 | 26 | grille_non_valide2 = [ 27 | [5, 9, 6, 1, 4, 2, 5, 3, 7], 28 | [6, 1, 4, 3, 5, 8, 2, 4, 8], 29 | [5, 6, 9, 4, 1, 2, 5, 3, 6], 30 | [1, 9, 5, 3, 6, 8, 4, 1, 6], 31 | [5, 9, 3, 6, 3, 4, 8, 2, 1], 32 | [5, 9, 5, 3, 2, 1, 4, 5, 6], 33 | [1, 3, 6, 4, 8, 6, 5, 2, 5], 34 | [4, 1, 2, 3, 6, 8, 4, 9, 2], 35 | [3, 6, 8, 7, 4, 1, 5, 6, 3] 36 | ] 37 | 38 | grille_non_valide3 = [ 39 | [4, 3, 5, 2, 6, 9, 7, 8, 1], 40 | [6, 8, 2, 5, 7, 1, 4, 9, 3], 41 | [1, 9, 7, 8, 3, 4, 5, 6, 2], 42 | [8, 2, 6, 1, 9, 5, 3, 4, 7], 43 | [3, 7, 4, 6, 8, 2, 9, 1, 5], 44 | [1, 5, 9, 7, 4, 3, 6, 2, 8], 45 | [5, 1, 9, 3, 2, 6, 8, 7, 4], 46 | [2, 4, 8, 9, 5, 7, 1, 3, 6], 47 | [7, 6, 3, 4, 1, 8, 2, 5, 9] 48 | ] 49 | 50 | def sudoku_est_valide(grille): 51 | 52 | #Test des lignes 53 | for line in grille: 54 | if not len(set(line)) == 9: 55 | return False 56 | 57 | #Test des colonnes 58 | for i in range(9): 59 | column = [] 60 | for j in range(9): 61 | column.append(grille[j][i]) 62 | if not len(set(column)) == 9: 63 | return False 64 | 65 | #On teste les sous-grilles 3x3 66 | for y0 in [0, 3, 6]: 67 | for x0 in [0, 3, 6]: 68 | subgrid = [] 69 | for i in range(0, 3): 70 | for j in range(0, 3): 71 | if grille[y0+i][x0+j] in subgrid: 72 | return False 73 | subgrid.append(grille[y0+i][x0+j]) 74 | 75 | return True 76 | 77 | print(sudoku_est_valide(grille_valide)) 78 | print(sudoku_est_valide(grille_non_valide)) 79 | print(sudoku_est_valide(grille_non_valide2)) 80 | print(sudoku_est_valide(grille_non_valide3)) 81 | -------------------------------------------------------------------------------- /116. Résoudre une grille de Sudoku/sudoku.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | grid = [] 4 | 5 | def n_valide(y, x, n): 6 | """Détermine si un nombre n peut être mis sur une case à la colonne x et à la ligne""" 7 | global grid 8 | #On détermine si le nombre est valide sur sa ligne 9 | for x0 in range(len(grid)): 10 | if grid[y][x0] == n: 11 | return False 12 | 13 | #On détermine si le nombre est valide sur sa colonne 14 | for y0 in range(len(grid)): 15 | if grid[y0][x] == n: 16 | return False 17 | 18 | x0 = (x//3) * 3 19 | y0= (y//3) * 3 20 | #On détermine si le nombre est valide dans sa sous-grille 3x3 21 | for i in range(0,3): 22 | for j in range(0,3): 23 | if grid[y0+i][x0+j] == n: 24 | return False 25 | return True 26 | 27 | def solve(): 28 | global grid 29 | for y in range(9): 30 | for x in range(9): 31 | if grid[y][x] == 0: 32 | for n in range(1,10): 33 | if n_valide(y, x, n): 34 | grid[y][x] = n 35 | solve() 36 | grid[y][x] = 0 37 | return 38 | for i in range(9): 39 | for j in range(9): 40 | print(grid[i][j], end="") 41 | print() 42 | exit(0) 43 | -------------------------------------------------------------------------------- /117. Afficher le triangle de Pascal/test_triangle_pascal.py: -------------------------------------------------------------------------------- 1 | from triangle_pascal import triangle_pascal 2 | 3 | print(triangle_pascal(7)) 4 | -------------------------------------------------------------------------------- /117. Afficher le triangle de Pascal/triangle_pascal.py: -------------------------------------------------------------------------------- 1 | def triangle_pascal(n): 2 | """Affiche les n premières lignes du triangle de Pascal""" 3 | 4 | if n == 0: 5 | return [] 6 | 7 | pascal = [[1]] 8 | 9 | for i in range(1,n): 10 | line = [1] 11 | for j in range(len(pascal)): 12 | if j+1 < len(pascal): 13 | line.append(pascal[i-1][j] + pascal[i-1][j+1]) 14 | line.append(1) 15 | pascal.append(line) 16 | 17 | return pascal 18 | 19 | -------------------------------------------------------------------------------- /118. Retourner les éléments présents dans deux listes/both_list.py: -------------------------------------------------------------------------------- 1 | def both_list(liste1, liste2): 2 | """Renvoie les éléments présents à la fois dans liste1 et liste2""" 3 | 4 | liste1 = sorted(set(liste1)) 5 | liste2 = sorted(set(liste2)) 6 | final_list = [] 7 | 8 | for element in liste1: 9 | if element in liste2 and not element in final_list: 10 | final_list.append(element) 11 | 12 | for element in liste2: 13 | if element in liste1 and not element in final_list: 14 | final_list.append(element) 15 | 16 | return final_list 17 | 18 | 19 | -------------------------------------------------------------------------------- /118. Retourner les éléments présents dans deux listes/test_both_list.py: -------------------------------------------------------------------------------- 1 | from both_list import both_list 2 | 3 | #Instanciation de liste1 et liste2 4 | liste1 = [] 5 | liste2 = [] 6 | 7 | #Premier test 8 | for i in range(1,21): 9 | liste1.append(i) 10 | for i in range(10,21): 11 | liste2.append(i) 12 | print(both_list(liste1, liste2)) 13 | 14 | #Second test 15 | liste1 = [1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2] 16 | liste2 = [4,5,6,7,8,9,10,11,12,13,14,15,1,18,19] 17 | print(both_list(liste1, liste2)) 18 | -------------------------------------------------------------------------------- /119. Somme de deux fractions/fraction.py: -------------------------------------------------------------------------------- 1 | def somme_fraction(numerateur1, denominateur1, numerateur2, denominateur2): 2 | 3 | #Si elles ont le même dénominateur 4 | if denominateur1 == denominateur2: 5 | return numerateur1+numerateur2, denominateur1 6 | 7 | else: 8 | denominateur = denominateur1*denominateur2 9 | numerateur1 = numerateur1 * denominateur2 10 | numerateur2 = numerateur2 * denominateur1 11 | 12 | return numerateur1+numerateur2, denominateur 13 | -------------------------------------------------------------------------------- /119. Somme de deux fractions/test_fraction.py: -------------------------------------------------------------------------------- 1 | from fraction import somme_fraction 2 | 3 | a,b,c,d = 1,2,1,3 4 | num, den = somme_fraction(a,b,c,d) 5 | print("{}/{} + {}/{} = {}/{}".format(a,b,c,d,num, den)) 6 | print() 7 | 8 | a,b,c,d = 1,2,1,4 9 | num, den = somme_fraction(a,b,c,d) 10 | print("{}/{} + {}/{} = {}/{}".format(a,b,c,d,num, den)) 11 | print() 12 | 13 | a,b,c,d = 1,3,1,4 14 | num, den = somme_fraction(a,b,c,d) 15 | print("{}/{} + {}/{} = {}/{}".format(a,b,c,d,num, den)) 16 | print() 17 | 18 | a,b,c,d = 1,5,1,10 19 | num, den = somme_fraction(a,b,c,d) 20 | print("{}/{} + {}/{} = {}/{}".format(a,b,c,d,num, den)) 21 | print() 22 | -------------------------------------------------------------------------------- /120. Les nombres de Tribonacci/test_tribonacci.py: -------------------------------------------------------------------------------- 1 | from tribonacci import tribonacci 2 | 3 | for i in range(1, 20): 4 | print(tribonacci(i)) 5 | -------------------------------------------------------------------------------- /120. Les nombres de Tribonacci/tribonacci.py: -------------------------------------------------------------------------------- 1 | def tribonacci(n): 2 | """La suite de tribonacci est comme la suite de fibonacci sauf qu'on fait la somme 3 | des 3 chiffres précédents dans la suite.""" 4 | 5 | serie = [0,1,1] 6 | while len(serie) <= n: 7 | serie.append(sum(serie[-3:])) 8 | return serie[n] 9 | -------------------------------------------------------------------------------- /121. Inverser tous les mots d'une chaîne de caractères/inverse.py: -------------------------------------------------------------------------------- 1 | def inverse(string): 2 | """Inverse l'ordre des lettres de tous les mots de la phrase""" 3 | 4 | return " ".join([word[::-1] for word in string.split(" ")]) 5 | -------------------------------------------------------------------------------- /122. Number complement/complement.py: -------------------------------------------------------------------------------- 1 | def complement(number): 2 | """Le complément d'un nombre est ce nombre avec tous les bits inversés""" 3 | 4 | new_number = "" 5 | 6 | if isinstance(number, int): 7 | number = bin(number) 8 | 9 | if "0b" in number: 10 | number = number.replace("0b", "") 11 | 12 | for bit in number: 13 | if bit == "0": 14 | new_number += "1" 15 | else: 16 | new_number += "0" 17 | 18 | return new_number 19 | 20 | -------------------------------------------------------------------------------- /122. Number complement/test_complement.py: -------------------------------------------------------------------------------- 1 | from complement import complement 2 | 3 | n = 10 4 | print(bin(n).replace("0b", "")) 5 | print(complement(n)) 6 | 7 | print("-------------------------") 8 | n = 256 9 | print(bin(n).replace("0b", "")) 10 | print(complement(n)) 11 | 12 | print("-------------------------") 13 | n = 188 14 | print(bin(n).replace("0b", "")) 15 | print(complement(n)) 16 | -------------------------------------------------------------------------------- /123. Coefficient binomial/binomial.py: -------------------------------------------------------------------------------- 1 | from math import factorial 2 | 3 | def coefficient_binomial(n, p): 4 | """Calcule le coefficient binomial""" 5 | 6 | return factorial(n) / (factorial(p) * factorial(n-p)) 7 | 8 | 9 | 10 | def display_coefficient_binomial(n,p): 11 | """Affiche l'égalité du calcul du coefficient binomial""" 12 | 13 | print("{}!/({}!*({} - {})!) = {}".format(n, p, n, p, coefficient_binomial(n,p))) 14 | -------------------------------------------------------------------------------- /123. Coefficient binomial/test_binomial.py: -------------------------------------------------------------------------------- 1 | from binomial import coefficient_binomial, display_coefficient_binomial 2 | 3 | display_coefficient_binomial(5,2) 4 | display_coefficient_binomial(10,3) 5 | display_coefficient_binomial(4,2) 6 | -------------------------------------------------------------------------------- /124. Ajouter des zéros au début d'un nombre/fill.py: -------------------------------------------------------------------------------- 1 | def fill(nombre, nb_de_zeros): 2 | """Ajoute des zéros au début d'un nombre entier""" 3 | 4 | if nb_de_zeros < 0: 5 | print("Le nombre de zéros ne peut être négatif") 6 | return None 7 | 8 | return "0"*nb_de_zeros+str(nombre) 9 | 10 | 11 | 12 | def fill_length(nombre, length): 13 | """Ajoute des zéros jusqu'à ce que le nombre entier soit composé de length caractères""" 14 | 15 | if length <= 0: 16 | return None 17 | 18 | if len(str(nombre)) >= length: 19 | return str(nombre) 20 | 21 | else: 22 | return "0"*(length - len(str(nombre)))+str(nombre) 23 | 24 | 25 | def z_fill(nombre, z): 26 | """Ajoute des zéros jusqu'à ce que le nombre entier soit composé de z caractères""" 27 | 28 | return str(nombre).zfill(z) 29 | -------------------------------------------------------------------------------- /124. Ajouter des zéros au début d'un nombre/test_fill.py: -------------------------------------------------------------------------------- 1 | from fill import fill, fill_length, z_fill 2 | 3 | print("Test de fill") 4 | nombre = 3 5 | nb_de_zeros = 2 6 | print("nombre : {}, nb_de_zeros : {}, fill : {}".format(nombre, nb_de_zeros, fill(nombre, nb_de_zeros))) 7 | 8 | nombre = 16 9 | nb_de_zeros = 5 10 | print("nombre : {}, nb_de_zeros : {}, fill : {}".format(nombre, nb_de_zeros, fill(nombre, nb_de_zeros))) 11 | 12 | nombre = 111 13 | nb_de_zeros = -5 14 | print("nombre : {}, nb_de_zeros : {}, fill : {}".format(nombre, nb_de_zeros, fill(nombre, nb_de_zeros))) 15 | 16 | print("\nTest de fill_length") 17 | nombre = 3 18 | length = 2 19 | print("nombre : {}, length: {}, fill : {}".format(nombre, length, fill_length(nombre, length))) 20 | 21 | nombre = 111 22 | length = 3 23 | print("nombre : {}, length: {}, fill : {}".format(nombre, length, fill_length(nombre, length))) 24 | 25 | nombre = 1234 26 | length = 3 27 | print("nombre : {}, length: {}, fill : {}".format(nombre, length, fill_length(nombre, length))) 28 | 29 | print("\n Test de z_fill") 30 | nombre = 1 31 | z = 3 32 | print("nombre : {}, z: {}, fill : {}".format(nombre, z, z_fill(nombre, z))) 33 | 34 | nombre = 123 35 | z = 2 36 | print("nombre : {}, z: {}, fill : {}".format(nombre, z, z_fill(nombre, z))) 37 | -------------------------------------------------------------------------------- /125. Trouver le PGCD/pgcd.py: -------------------------------------------------------------------------------- 1 | def pgcd(x,y): 2 | """Renvoie le PGCD des nombres x et y""" 3 | 4 | if x < y: 5 | x, y = y, x 6 | 7 | #Si y est un diviseur de x, alors le PGCD est y 8 | if x % y == 0: 9 | return y 10 | 11 | #On recherche un diviseur commun en partant de y/2 en allant jusqu'à 0 12 | for k in range(y//2, 0, -1): 13 | if x % k == 0 and y % k == 0: 14 | return k 15 | 16 | -------------------------------------------------------------------------------- /125. Trouver le PGCD/test_pgcd.py: -------------------------------------------------------------------------------- 1 | from pgcd import pgcd 2 | 3 | x = 10 4 | y = 4 5 | print("x = {}, y = {}, pgcd = {}".format(x, y, pgcd(x,y))) 6 | 7 | x=9 8 | y=3 9 | print("x = {}, y = {}, pgcd = {}".format(x, y, pgcd(x,y))) 10 | 11 | x=91 12 | y=7 13 | print("x = {}, y = {}, pgcd = {}".format(x, y, pgcd(x,y))) 14 | 15 | x=92 16 | y=7 17 | print("x = {}, y = {}, pgcd = {}".format(x, y, pgcd(x,y))) 18 | -------------------------------------------------------------------------------- /126. Initialiser une matrice identité/identity.py: -------------------------------------------------------------------------------- 1 | def identity(n): 2 | """Créée une matrice identité de taille nxn""" 3 | 4 | matrix = [] 5 | for i in range(n): 6 | line = [] 7 | for j in range(n): 8 | if i == j: 9 | line.append(1) 10 | else: 11 | line.append(0) 12 | matrix.append(line) 13 | 14 | return matrix 15 | 16 | 17 | 18 | def matrice_nulle(M, N): 19 | """Instancie une matrice nulle avec M lignes et N colonnes 20 | Ici, une matrice est une liste de listes""" 21 | 22 | matrice = [] 23 | for i in range(M): 24 | matrice.append([0 for x in range(N)]) 25 | return matrice 26 | 27 | 28 | 29 | def alt_identity(n): 30 | """Créée une matrice identité de taille nxn""" 31 | 32 | matrix = matrice_nulle(n,n) 33 | for i in range(n): 34 | matrix[i][i] = 1 35 | 36 | return matrix 37 | -------------------------------------------------------------------------------- /126. Initialiser une matrice identité/test_identity.py: -------------------------------------------------------------------------------- 1 | from identity import identity, alt_identity 2 | from pprint import pprint 3 | 4 | for i in range(1, 11): 5 | print("--------- {} ---------- \n".format(i)) 6 | pprint(identity(i)) 7 | print() 8 | pprint(alt_identity(i)) 9 | print() 10 | -------------------------------------------------------------------------------- /127. Convertir une chaîne de caractères en Morse/morse.py: -------------------------------------------------------------------------------- 1 | def word_to_morse(word): 2 | """Convertie un mot en morse""" 3 | 4 | code = { "a" : ".-", 5 | "b" : "-...", 6 | "c" : "-.-.", 7 | "d" : "-..", 8 | "e" : ".", 9 | "f" : "..-.", 10 | "g" : "--.", 11 | "h" : "....", 12 | "i" : "..", 13 | "j" : ".---", 14 | "k" : "-.-", 15 | "l" : ".-..", 16 | "m" : "--", 17 | "n" : "-.", 18 | "o" : "---", 19 | "p" : ".--.", 20 | "q" : "--.-", 21 | "r" : ".-.", 22 | "s" : "...", 23 | "t" : "-", 24 | "u" : "..-", 25 | "v" : "...-", 26 | "w" : ".--", 27 | "x" : "-..-", 28 | "y" : "-.--", 29 | "z" : "--..", 30 | "1" : ".----", 31 | "2" : "..---", 32 | "3" : "...--", 33 | "4" : "....-", 34 | "5" : ".....", 35 | "6" : "-....", 36 | "7" : "--...", 37 | "8" : "---..", 38 | "9" : "----.", 39 | "0" : "-----" 40 | } 41 | 42 | morse_word = [] 43 | for char in word: 44 | morse_word.append(code[char.lower()]) 45 | 46 | return " ".join(morse_word) 47 | 48 | 49 | 50 | def string_to_morse(string): 51 | """Convertie une phrase en morse""" 52 | 53 | string = string.split(" ") 54 | morse_string = [] 55 | 56 | for word in string: 57 | morse_string.append(word_to_morse(word)) 58 | 59 | return " ".join(morse_string) 60 | 61 | -------------------------------------------------------------------------------- /127. Convertir une chaîne de caractères en Morse/test_morse.py: -------------------------------------------------------------------------------- 1 | from morse import word_to_morse, string_to_morse 2 | 3 | print(word_to_morse("SOS")) 4 | print(string_to_morse("Hello world")) 5 | print(word_to_morse("Foxxpy")) 6 | -------------------------------------------------------------------------------- /128. Additionner deux nombres complexes/complexe.py: -------------------------------------------------------------------------------- 1 | 2 | class Complexe: 3 | 4 | def __init__(self, real, imaginary): 5 | self.re = real 6 | self.im = imaginary 7 | 8 | 9 | def __str__(self): 10 | if self.im < 0: 11 | return "{} - {}i".format(self.re, abs(self.im)) 12 | 13 | elif self.im > 0: 14 | return "{} + {}i".format(self.re, self.im) 15 | 16 | else: 17 | return "{}".format(self.re) 18 | 19 | 20 | def __add__(self, other): 21 | return Complexe(self.re+other.re, self.im + other.im) 22 | 23 | 24 | -------------------------------------------------------------------------------- /128. Additionner deux nombres complexes/complexe_2.py: -------------------------------------------------------------------------------- 1 | def somme_complexe(z1, z2): 2 | z_reel = z1[0] + z2[0] 3 | z_img = z1[1] + z2[1] 4 | 5 | return (z_reel, z_img) 6 | 7 | 8 | def print_complexe(z): 9 | """Affiche le nombre complexe z""" 10 | 11 | print("{} + {}i".format(z[0], z[1])) 12 | 13 | -------------------------------------------------------------------------------- /128. Additionner deux nombres complexes/test_complexe.py: -------------------------------------------------------------------------------- 1 | from complexe import Complexe 2 | 3 | a = Complexe(1, 1) 4 | b = Complexe(2, 3) 5 | print(a+b) 6 | 7 | a = Complexe(-2,-3) 8 | b = Complexe(4, -9) 9 | print(a+b) 10 | -------------------------------------------------------------------------------- /128. Additionner deux nombres complexes/test_complexe_2.py: -------------------------------------------------------------------------------- 1 | from complexe_2 import somme_complexe, print_complexe 2 | 3 | z1 = (1,2) 4 | z2 = (3,-2) 5 | z3 = (0, -6) 6 | z4 = (3, 7) 7 | z5 = (-2, -2) 8 | z6 = (-3, -4) 9 | 10 | print_complexe(somme_complexe(z1, z2)) 11 | print_complexe(somme_complexe(z3, z4)) 12 | print_complexe(somme_complexe(z5, z6)) -------------------------------------------------------------------------------- /129. Multiplier deux nombres complexes/complexe.py: -------------------------------------------------------------------------------- 1 | class Complexe: 2 | 3 | def __init__(self, real, imaginary): 4 | """Initialise les attributs représentant les nombres réels et imaginaires. 5 | :type self: Complexe 6 | :type real: float 7 | :type imaginary: float""" 8 | 9 | self.re = real 10 | self.im = imaginary 11 | 12 | 13 | def __str__(self): 14 | """Renvoie ce nombre Complexe sous forme de chaîne de caractères. 15 | :type self: Complexe 16 | :rtype: str""" 17 | 18 | if self.im < 0: 19 | return "{} - {}i".format(self.re, abs(self.im)) 20 | 21 | elif self.im > 0: 22 | return "{} + {}i".format(self.re, self.im) 23 | 24 | else: 25 | return "{}".format(self.re) 26 | 27 | 28 | def __mul__(self, other): 29 | """Multiplie ce nombre complexe avec un autre nombre complexe. 30 | :type self: Complexe 31 | :type other: Complexe 32 | :rtype: Complexe 33 | """ 34 | 35 | new_real = self.re * other.re - self.im * other.im 36 | new_im = self.im * other.re + self.re * other.im 37 | return Complexe(new_real, new_im) 38 | 39 | 40 | def __add__(self, other): 41 | """Additionner ce nombre complexe avec un autre nombre complexe. 42 | :type self: Complexe 43 | :type other: Complexe 44 | :rtype: Complexe""" 45 | 46 | return Complexe(self.re+other.re, self.im + other.im) 47 | 48 | 49 | -------------------------------------------------------------------------------- /129. Multiplier deux nombres complexes/complexe_2.py: -------------------------------------------------------------------------------- 1 | def produit_complexe(z1, z2): 2 | """Multiplie le nombre complexe z1 avec le nombre complexe z2. 3 | :type z1: tuple 4 | :type z2: tuple 5 | :rtype: tuple 6 | """ 7 | 8 | z_reel = z1[0] * z2[0] - z1[1] * z2[1] 9 | z_im = z1[0] * z2[1] + z1[1] * z2[0] 10 | return (z_reel, z_im) 11 | 12 | 13 | 14 | def print_complexe(z): 15 | """Affiche le nombre complexe z. 16 | :type z: tuple 17 | """ 18 | 19 | print("{} + {}i".format(z[0], z[1])) -------------------------------------------------------------------------------- /129. Multiplier deux nombres complexes/test_complexe.py: -------------------------------------------------------------------------------- 1 | from complexe import Complexe 2 | 3 | #Instanciation des nombres complexes 4 | real = 0 5 | imaginary = 1 6 | real_2 = 10 7 | imaginary_2 = 1 8 | 9 | #Test des méthodes multipliant les nombres complexes 10 | a = Complexe(real, imaginary) 11 | b = Complexe(real_2, imaginary_2) 12 | print(a*b) 13 | print(complex(real,imaginary)*complex(real_2,imaginary_2)) 14 | -------------------------------------------------------------------------------- /129. Multiplier deux nombres complexes/test_complexe_2.py: -------------------------------------------------------------------------------- 1 | from complexe_2 import produit_complexe 2 | 3 | #Instanciation des nombres complexes 4 | z1 = (1,1) 5 | z2 = (3,2) 6 | 7 | z3 = (5,0) 8 | z4 = (2,2) 9 | 10 | z5 = (1,-2) 11 | z6 = (3, -1) 12 | 13 | #Test des méthodes multipliant les nombres complexes 14 | print(produit_complexe(z1,z2)) 15 | print((1+1j)*(3+2j)) 16 | print(produit_complexe(z3,z4)) 17 | print((5+0j)*(2+2j)) 18 | print(produit_complexe(z5,z6)) 19 | print((1-2j)*(3-1j)) -------------------------------------------------------------------------------- /130. Négation d'un nombre complexe/complexe.py: -------------------------------------------------------------------------------- 1 | 2 | class Complexe: 3 | 4 | def __init__(self, real, imaginary): 5 | self.re = real 6 | self.im = imaginary 7 | 8 | 9 | def __str__(self): 10 | if self.im < 0: 11 | return "{} - {}i".format(self.re, abs(self.im)) 12 | 13 | elif self.im > 0: 14 | return "{} + {}i".format(self.re, self.im) 15 | 16 | else: 17 | return "{}".format(self.re) 18 | 19 | 20 | def negation(self): 21 | self.re = -1 * self.re 22 | self.im = -1 * self.im 23 | return self -------------------------------------------------------------------------------- /130. Négation d'un nombre complexe/complexe_2.py: -------------------------------------------------------------------------------- 1 | def negation_complexe(z): 2 | """Calcule la négation d'un nombre complexe""" 3 | 4 | return (-z[0], -z[1]) 5 | 6 | def print_complexe(z): 7 | """Affiche le nombre complexe z""" 8 | 9 | print("{} + {}i".format(z[0], z[1])) -------------------------------------------------------------------------------- /130. Négation d'un nombre complexe/test_complexe.py: -------------------------------------------------------------------------------- 1 | from complexe import Complexe 2 | 3 | #On créé des nombres complexes 4 | z1 = Complexe(1, 2) 5 | z2 = Complexe(-5, -7) 6 | z3 = Complexe(6, 0) 7 | z4 = Complexe(0, -8) 8 | 9 | #On teste si la négation fonctionne 10 | print(z1.negation()) 11 | print(z2.negation()) 12 | print(z3.negation()) 13 | print(z4.negation()) -------------------------------------------------------------------------------- /130. Négation d'un nombre complexe/test_complexe2.py: -------------------------------------------------------------------------------- 1 | from complexe_2 import * 2 | 3 | #On créé des nombres complexes 4 | z1 = (1, 2) 5 | z2 = (-5, -7) 6 | z3 = (6, 0) 7 | z4 = (0, -8) 8 | 9 | #On affiche la négation des nombres complexes 10 | print_complexe(negation_complexe(z1)) 11 | print_complexe(negation_complexe(z2)) 12 | print_complexe(negation_complexe(z3)) 13 | print_complexe(negation_complexe(z4)) -------------------------------------------------------------------------------- /131. Inverse d'un nombre complexe/complexe.py: -------------------------------------------------------------------------------- 1 | class Complexe: 2 | 3 | def __init__(self, real, imaginary): 4 | self.re = real 5 | self.im = imaginary 6 | 7 | 8 | def __str__(self): 9 | """Renvoie le nombre complexe sous forme de chaîne de caractères.""" 10 | 11 | if self.im < 0: 12 | return "{} - {}i".format(self.re, abs(self.im)) 13 | 14 | elif self.im > 0: 15 | return "{} + {}i".format(self.re, self.im) 16 | 17 | else: 18 | return "{}".format(self.re) 19 | 20 | 21 | def inverse(self): 22 | """Calcule l'inverse de ce nombre complexe""" 23 | 24 | denominateur = self.re**2 + self.im**2 25 | self.re = self.re / denominateur 26 | self.im = -self.im / denominateur 27 | return self -------------------------------------------------------------------------------- /131. Inverse d'un nombre complexe/complexe_2.py: -------------------------------------------------------------------------------- 1 | def inverse_complexe(z): 2 | """Calcule l'inverse du nombre complexe z: 3 | :type z: tuple 4 | :rtype: tuple 5 | """ 6 | 7 | denominateur = z[0]**2 + z[1]**2 8 | reel = z[0] / denominateur 9 | im = -z[1] / denominateur 10 | return (reel, im) 11 | 12 | def print_complexe(z): 13 | """Affiche le nombre complexe z. 14 | :type z: tuple 15 | """ 16 | 17 | print("{} + {}i".format(z[0], z[1])) 18 | -------------------------------------------------------------------------------- /131. Inverse d'un nombre complexe/test_complexe.py: -------------------------------------------------------------------------------- 1 | #On importe la classe Complexe du module complexe 2 | from complexe import Complexe 3 | 4 | #On créé nos nombres complexes 5 | z1 = Complexe(1, 1) 6 | z2 = Complexe(3, 0) 7 | z3 = Complexe(0, -2) 8 | z4 = Complexe(4, 3) 9 | z5 = Complexe(-3, -2) 10 | 11 | #On affiche l'inverse des nombres complexes 12 | print(z1.inverse()) 13 | print(z2.inverse()) 14 | print(z3.inverse()) 15 | print(z4.inverse()) 16 | print(z5.inverse()) -------------------------------------------------------------------------------- /131. Inverse d'un nombre complexe/test_complexe_2.py: -------------------------------------------------------------------------------- 1 | #On importe toutes les méthodes du module complexe_2 2 | from complexe_2 import * 3 | 4 | #On créé nos nombres complexes 5 | z1 = (1, 1) 6 | z2 = (3, 0) 7 | z3 = (0, -2) 8 | z4 = (4, 3) 9 | z5 = (-3, -2) 10 | 11 | #On affiche l'inverse des nombres complexes précédents 12 | print_complexe(inverse_complexe(z1)) 13 | print_complexe(inverse_complexe(z2)) 14 | print_complexe(inverse_complexe(z3)) 15 | print_complexe(inverse_complexe(z4)) 16 | print_complexe(inverse_complexe(z5)) -------------------------------------------------------------------------------- /132. Le conjugué d'un nombre complexe/complexe.py: -------------------------------------------------------------------------------- 1 | class Complexe: 2 | 3 | def __init__(self, real, imaginary): 4 | self.re = real 5 | self.im = imaginary 6 | 7 | 8 | def __str__(self): 9 | """Renvoie le nombre complexe sous forme de chaîne de caractères.""" 10 | if self.im < 0: 11 | return "{} - {}i".format(self.re, abs(self.im)) 12 | 13 | elif self.im > 0: 14 | return "{} + {}i".format(self.re, self.im) 15 | 16 | else: 17 | return "{}".format(self.re) 18 | 19 | 20 | def conjugue(self): 21 | """Calcule le conjugué de ce nombre complexe""" 22 | 23 | self.im = -self.im 24 | return self -------------------------------------------------------------------------------- /132. Le conjugué d'un nombre complexe/complexe_2.py: -------------------------------------------------------------------------------- 1 | def conjugue_complexe(z): 2 | """Calcule le conjugué d'un nombre complexe z""" 3 | 4 | return (z[0], -z[1]) 5 | 6 | 7 | 8 | def print_complexe(z): 9 | """Affiche le nombre complexe z""" 10 | 11 | print("{} + {}i".format(z[0], z[1])) -------------------------------------------------------------------------------- /132. Le conjugué d'un nombre complexe/test_complexe.py: -------------------------------------------------------------------------------- 1 | from complexe import Complexe 2 | 3 | #On créé des nombres complexes 4 | z1 = Complexe(1, 1) 5 | z2 = Complexe(2, 0) 6 | z3 = Complexe(0, -6) 7 | z4 = Complexe(-4, -10) 8 | z5 = Complexe(-5, 1) 9 | 10 | #On calcule le conjugué des nombres complexes précédents 11 | print(z1.conjugue()) 12 | print(z2.conjugue()) 13 | print(z3.conjugue()) 14 | print(z4.conjugue()) 15 | print(z5.conjugue()) -------------------------------------------------------------------------------- /132. Le conjugué d'un nombre complexe/test_complexe_2.py: -------------------------------------------------------------------------------- 1 | from complexe_2 import * 2 | 3 | #On créé des nombres complexes 4 | z1 = (1, 1) 5 | z2 = (2, 0) 6 | z3 = (0, -6) 7 | z4 = (-4, -10) 8 | z5 = (-5, 1) 9 | 10 | #On affiche le conjugué des nombres complexes précédents 11 | print_complexe(conjugue_complexe(z1)) 12 | print_complexe(conjugue_complexe(z2)) 13 | print_complexe(conjugue_complexe(z3)) 14 | print_complexe(conjugue_complexe(z4)) 15 | print_complexe(conjugue_complexe(z5)) -------------------------------------------------------------------------------- /133. Le module d'un nombre complexe/complexe.py: -------------------------------------------------------------------------------- 1 | class Complexe: 2 | 3 | def __init__(self, real, imaginary): 4 | self.re = real 5 | self.im = imaginary 6 | 7 | 8 | def __str__(self): 9 | """Renvoie ce nombre complexe sous forme de chaîne de caractères.""" 10 | if self.im < 0: 11 | return "{} - {}i".format(self.re, abs(self.im)) 12 | 13 | elif self.im > 0: 14 | return "{} + {}i".format(self.re, self.im) 15 | 16 | else: 17 | return "{}".format(self.re) 18 | 19 | 20 | def module(self): 21 | """Renvoie le module de ce nombre complexe""" 22 | 23 | sum_square = self.re**2 + self.im**2 24 | return sum_square**(1/2) -------------------------------------------------------------------------------- /133. Le module d'un nombre complexe/complexe_2.py: -------------------------------------------------------------------------------- 1 | def module_complexe(z): 2 | """Calcule le module du nombre complexe z""" 3 | 4 | sum_square = z[0]**2 + z[1]**2 5 | return sum_square**(1/2) 6 | 7 | 8 | 9 | def print_complexe(z): 10 | """Affiche le nombre complexe z""" 11 | 12 | print("{} + {}i".format(z[0], z[1])) -------------------------------------------------------------------------------- /133. Le module d'un nombre complexe/test_complexe.py: -------------------------------------------------------------------------------- 1 | from complexe import Complexe 2 | 3 | #On créé nos nombres complexes 4 | z1 = Complexe(1, 2) 5 | z2 = Complexe(3, 0) 6 | z3 = Complexe(0, -5) 7 | z4 = Complexe(4, 5) 8 | z5 = Complexe(-1, -1) 9 | 10 | #On calcule le module des nombres complexes précédents 11 | print(z1.module()) 12 | print(z2.module()) 13 | print(z3.module()) 14 | print(z4.module()) 15 | print(z5.module()) -------------------------------------------------------------------------------- /133. Le module d'un nombre complexe/test_complexe_2.py: -------------------------------------------------------------------------------- 1 | from complexe_2 import * 2 | 3 | #On créé nos nombres complexes 4 | z1 = (1, 2) 5 | z2 = (3, 0) 6 | z3 = (0, -5) 7 | z4 = (4, 5) 8 | z5 = (-1, -1) 9 | 10 | #On calcule le module des nombres complexes précédents 11 | print(module_complexe(z1)) 12 | print(module_complexe(z2)) 13 | print(module_complexe(z3)) 14 | print(module_complexe(z4)) 15 | print(module_complexe(z5)) -------------------------------------------------------------------------------- /134. Argument d'un nombre complexe/complexe.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Complexe: 4 | 5 | def __init__(self, real, imaginary): 6 | self.re = real 7 | self.im = imaginary 8 | 9 | 10 | def __str__(self): 11 | """Renvoie le nombre complexe sous forme de chaîne de caractères.""" 12 | if self.im < 0: 13 | return "{} - {}i".format(self.re, abs(self.im)) 14 | 15 | elif self.im > 0: 16 | return "{} + {}i".format(self.re, self.im) 17 | 18 | else: 19 | return "{}".format(self.re) 20 | 21 | 22 | 23 | def module(self): 24 | """Renvoie le module de ce nombre complexe""" 25 | 26 | sum_square = self.re**2 + self.im**2 27 | return sum_square**(1/2) 28 | 29 | 30 | 31 | def argument(self, degree=True): 32 | """Renvoie l'argument de ce nombre complexe""" 33 | 34 | arg = math.acos(self.re / self.module()) 35 | 36 | if self.im < 0: 37 | arg = -arg 38 | 39 | if degree: 40 | return math.degrees(arg) 41 | return arg -------------------------------------------------------------------------------- /134. Argument d'un nombre complexe/complexe_2.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def module_complexe(z): 4 | """Calcule le module du nombre complexe z""" 5 | 6 | sum_square = z[0]**2 + z[1]**2 7 | return sum_square**(1/2) 8 | 9 | 10 | def argument_complexe(z, degree=True): 11 | """Calcule l'argument du nombre complexe z""" 12 | 13 | arg = math.acos(z[0] / module_complexe(z)) 14 | if z[1] < 0: 15 | arg = -arg 16 | 17 | if degree: 18 | return math.degrees(arg) 19 | return arg 20 | 21 | 22 | def print_complexe(z): 23 | """Affiche le nombre complexe z""" 24 | 25 | print("{} + {}i".format(z[0], z[1])) -------------------------------------------------------------------------------- /134. Argument d'un nombre complexe/test_complexe.py: -------------------------------------------------------------------------------- 1 | from complexe import Complexe 2 | import cmath, math 3 | #On créé nos nombres complexes 4 | z1 = Complexe(1,1) 5 | z2 = Complexe(0, 1) 6 | z3 = Complexe(-1, -1) 7 | z4 = Complexe(-1, 0) 8 | 9 | # On calcule l'argument de nos nombres complexes précédents 10 | print(z1.argument()) 11 | print(math.degrees(cmath.phase(1+1j))) 12 | print("-----") 13 | 14 | print(z2.argument()) 15 | print(math.degrees(cmath.phase(1j))) 16 | print("-----") 17 | 18 | print(z3.argument()) 19 | print(math.degrees(cmath.phase(-1-1j))) 20 | print("-----") 21 | 22 | print(z4.argument()) 23 | print(math.degrees(cmath.phase(-1-0j))) -------------------------------------------------------------------------------- /134. Argument d'un nombre complexe/test_complexe_2.py: -------------------------------------------------------------------------------- 1 | from complexe_2 import * 2 | import cmath, math 3 | 4 | #On créé nos nombres complexes 5 | z1 = (1,1) 6 | z2 = (0, 1) 7 | z3 = (-1, -1) 8 | z4 = (-1, 0) 9 | 10 | #On calcule l'argument des nombres complexes précédents 11 | print(argument_complexe(z1)) 12 | print(math.degrees(cmath.phase(1+1j))) 13 | print("-----") 14 | 15 | print(argument_complexe(z2)) 16 | print(math.degrees(cmath.phase(1j))) 17 | print("-----") 18 | 19 | print(argument_complexe(z3)) 20 | print(math.degrees(cmath.phase(-1-1j))) 21 | print("-----") 22 | 23 | print(argument_complexe(z4)) 24 | print(math.degrees(cmath.phase(-1-0j))) -------------------------------------------------------------------------------- /135. Trouver l'expression du nombre imaginaire i^n/expression_i.py: -------------------------------------------------------------------------------- 1 | def power_i(n): 2 | """Renvoie la valeur de i à la puissance n. 3 | :type n: int 4 | :rtype: Complex 5 | """ 6 | if n % 4 == 1: 7 | return 1j 8 | 9 | elif n % 4 == 2: 10 | return -1 + 0j 11 | 12 | elif n % 4 == 3: 13 | return -1j 14 | 15 | else: 16 | return 1 + 0j -------------------------------------------------------------------------------- /135. Trouver l'expression du nombre imaginaire i^n/test_expression_i.py: -------------------------------------------------------------------------------- 1 | from expression_i import power_i 2 | 3 | for i in range(50): 4 | print("i^{} = {}".format(i, power_i(i))) 5 | -------------------------------------------------------------------------------- /136. Récupérer un nombre complexe depuis une chaîne de caractères/complexe_parser.py: -------------------------------------------------------------------------------- 1 | def string_to_complex(string): 2 | """Renvoie la valeur réelle et la valeur imaginaire d'un nombre complexe dans deux variables distinctes 3 | :type string: str - Nombre complexe contenu dans une chaîne de caractères 4 | :rtype: tuple(int, int) 5 | """ 6 | #On retire les espaces 7 | string = string.replace(" ", "") 8 | reel, im = 0, 1j 9 | i = 0 10 | while i < len(string): 11 | if i != 0 and string[i] in ["+", "-"]: 12 | #Si string[i] est égal à "+" ou "-" et que le caractère précédent est un "e", on ne casse pas la boucle, on continue 13 | if i > 0 and string[i-1] != "e": 14 | break 15 | i += 1 16 | 17 | #Si la première partie de la chaîne de caractères contient le i ou le j 18 | if "i" in string[:i] or "j" in string[:i]: 19 | im = 0 if len(string[:i]) == 0 else float(string[:i].replace("i", "").replace("j", "")) 20 | reel = 0 if len(string[i:]) == 0 else float(string[i:]) 21 | 22 | #Si la seconde partie de la chaîne de caractères contient le i ou le j 23 | elif "i" in string[i:] or "j" in string[i:]: 24 | print(string[:i], string[i:]) 25 | im = 0 if len(string[i:]) == 0 else float(string[i:].replace("i", "").replace("j", "")) 26 | reel = 0 if len(string[:i]) == 0 else float(string[:i]) 27 | 28 | #Si il n'y a pas de i ou de j 29 | else: 30 | reel = float(string) 31 | im = 0 32 | 33 | return reel, im 34 | 35 | 36 | 37 | def string_to_complex_2(string): 38 | """Renvoie un nombre complexe dans un objet 'complex' de Python 39 | :type string: str 40 | :rtype: Complex 41 | """ 42 | 43 | string = string.replace(" ", "").replace("i", "j") 44 | return complex(string) 45 | 46 | -------------------------------------------------------------------------------- /136. Récupérer un nombre complexe depuis une chaîne de caractères/test_complexe_parser.py: -------------------------------------------------------------------------------- 1 | from complexe_parser import * 2 | 3 | #On créé nos nombres complexes 4 | z1 = "2 + 5i" 5 | z2 = "-1 - 2i" 6 | z3 = "10i" 7 | z4 = "-16" 8 | z5 = " 3 - 5j " 9 | z6 = "1.3 + 2.5j" 10 | z7 = "10e5 - 1.066j" 11 | z8 = "5e2" 12 | z9 = "-3e-2j" 13 | z10 = "-5e-5 - 10e-2j" 14 | 15 | #On teste la méthode string_to_complex() 16 | print(" ---- string_to_complex() ----") 17 | print(z1, ":", string_to_complex(z1)) 18 | print(z2, ":", string_to_complex(z2)) 19 | print(z3, ":", string_to_complex(z3)) 20 | print(z4, ":", string_to_complex(z4)) 21 | print(z5, ":", string_to_complex(z5)) 22 | print(z6, ":", string_to_complex(z6)) 23 | print(z7, ":", string_to_complex(z7)) 24 | print(z8, ":", string_to_complex(z8)) 25 | print(z9, ":", string_to_complex(z9)) 26 | print(z10, ":", string_to_complex(z10)) 27 | 28 | #On teste la méthode string_to_complex_2() 29 | print(" ---- string_to_complex_2() ----") 30 | print(z1, ":", string_to_complex_2(z1)) 31 | print(z2, ":", string_to_complex_2(z2)) 32 | print(z3, ":", string_to_complex_2(z3)) 33 | print(z4, ":", string_to_complex_2(z4)) 34 | print(z5, ":", string_to_complex_2(z5)) 35 | print(z6, ":", string_to_complex_2(z6)) 36 | print(z7, ":", string_to_complex_2(z7)) 37 | print(z8, ":", string_to_complex_2(z8)) 38 | print(z9, ":", string_to_complex_2(z9)) 39 | print(z10, ":", string_to_complex_2(z10)) -------------------------------------------------------------------------------- /137. Additionner deux matrices/add_matrix.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def add_matrix_basic(matrix_a, matrix_b): 4 | """Additionner les deux matrices envoyées en paramètres. 5 | :type matrix_a: list[list[float]] 6 | :type matrix_b: list[list[float]] 7 | :rtype: list[list[float]] 8 | """ 9 | 10 | if len(matrix_a) != len(matrix_b) or len(matrix_a[0]) != len(matrix_b[0]): 11 | return None 12 | 13 | new_matrix = [] 14 | 15 | for line in range(len(matrix_a)): 16 | line_matrix = [] 17 | for col in range(len(matrix_a[line])): 18 | line_matrix.append(matrix_a[line][col] + matrix_b[line][col]) 19 | new_matrix.append(line_matrix) 20 | 21 | return new_matrix 22 | 23 | 24 | def add_matrix(matrix_a, matrix_b): 25 | """Additionner les deux matrices envoyées en paramètres. 26 | :type matrix_a: list[list[float]] 27 | :type matrix_b: list[list[float]] 28 | :rtype: list[list[float]] 29 | """ 30 | 31 | if len(matrix_a) != len(matrix_b) or len(matrix_a[0]) != len(matrix_b[0]): 32 | return None 33 | 34 | new_matrix = [] 35 | for i in range(len(matrix_a)): 36 | line = [sum(x) for x in zip(matrix_a[i], matrix_b[i])] 37 | new_matrix.append(line) 38 | 39 | return new_matrix 40 | 41 | 42 | 43 | def add_matrix_np(matrix_a, matrix_b): 44 | """Additionner les deux matrices envoyées en paramètres. 45 | :type matrix_a: ndarray 46 | :type matrix_b: ndarray 47 | :rtype: ndarray 48 | """ 49 | 50 | matrix_a = np.array(matrix_a) 51 | matrix_b = np.array(matrix_b) 52 | 53 | return matrix_a + matrix_b 54 | -------------------------------------------------------------------------------- /137. Additionner deux matrices/test_add_matrix.py: -------------------------------------------------------------------------------- 1 | from add_matrix import add_matrix, add_matrix_np, add_matrix_basic 2 | 3 | #On créé nos matrices pour les tests 4 | a1 = [[1,2,3], [1,2,3]] 5 | a2 = [[3,2,1], [3,2,1]] 6 | 7 | b1 = [[1,2,3,4], [-1,-2,-3,-4], [0,1,0,1]] 8 | b2 = [[1,0,1,0], [1,2,3,4], [-1,-2,-3,-4]] 9 | 10 | c1 = [[1]] 11 | c2 = [[4]] 12 | 13 | #On affiche les résultats pour add_matrix_basic 14 | print("---- add_matrix_basic ----") 15 | print(add_matrix_basic(a1,a2)) 16 | print(add_matrix_basic(b1,b2)) 17 | print(add_matrix_basic(c1,c2)) 18 | 19 | #On affiche les résultats pour add_matrix 20 | print("---- add_matrix_ ----") 21 | print(add_matrix(a1,a2)) 22 | print(add_matrix(b1,b2)) 23 | print(add_matrix(c1,c2)) 24 | 25 | #On affiche les résultats pour add_matrix_np 26 | print("---- add_matrix_np ----") 27 | print(add_matrix_np(a1,a2)) 28 | print(add_matrix_np(b1,b2)) 29 | print(add_matrix_np(c1,c2)) -------------------------------------------------------------------------------- /138. Calculer la transposée d'une matrice/test_transpose.py: -------------------------------------------------------------------------------- 1 | from transpose import * 2 | 3 | #On créé nos matrices de test 4 | A = [[1,2,3], [4,5,6]] # matrice 2x3 5 | B = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20]] # matrice 4x5 6 | C = [[1,2], [3,4], [5,6], [7,8], [9,10]] # matrice 5x2 7 | 8 | #On teste la méthode tranpose() 9 | print(transpose(A)) 10 | print(transpose(B)) 11 | print(transpose(C)) -------------------------------------------------------------------------------- /138. Calculer la transposée d'une matrice/transpose.py: -------------------------------------------------------------------------------- 1 | def transpose(matrix): 2 | """Renvoie la transposée d'une matrice 3 | :type matrix: list[list[float]] 4 | :rtype: list[list[float]] 5 | """ 6 | 7 | result_matrix = [] 8 | 9 | for col in range(len(matrix[0])): 10 | line_matrix = [] 11 | for line in range(len(matrix)): 12 | line_matrix.append(matrix[line][col]) 13 | result_matrix.append(line_matrix) 14 | 15 | return result_matrix -------------------------------------------------------------------------------- /139. Produit d'Hadamard de deux matrices/hadamard.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def produit_hadamard(matrix_a, matrix_b): 4 | """Renvoie le produit d'Hadamard de deux matrices sous forme de liste de listes. 5 | :type matrix_a: list[list[float]] 6 | :type matrix_b: list[list[float]] 7 | :rtype: list[list[float]] 8 | """ 9 | 10 | if len(matrix_a) != len(matrix_b) or len(matrix_a[0]) != len(matrix_b[0]): 11 | return None 12 | 13 | result_matrix = list() 14 | for i in range(len(matrix_a)): 15 | matrix_line = [] 16 | for j in range(len(matrix_a[i])): 17 | matrix_line.append(matrix_a[i][j] * matrix_b[i][j]) 18 | result_matrix.append(matrix_line) 19 | 20 | return result_matrix 21 | 22 | 23 | 24 | def produit_hadamard_2(matrix_a, matrix_b): 25 | """Renvoie le produit d'Hadamard de deux matrices sous forme de liste de listes. 26 | :type matrix_a: list[list[float]] 27 | :type matrix_b: list[list[float]] 28 | :rtype: list[list[float]] 29 | """ 30 | 31 | if len(matrix_a) != len(matrix_b) or len(matrix_a[0]) != len(matrix_b[0]): 32 | return None 33 | 34 | new_matrix = [] 35 | for i in range(len(matrix_a)): 36 | line = [math.prod(x) for x in zip(matrix_a[i], matrix_b[i])] 37 | new_matrix.append(line) 38 | 39 | return new_matrix -------------------------------------------------------------------------------- /139. Produit d'Hadamard de deux matrices/test_hadamard.py: -------------------------------------------------------------------------------- 1 | from hadamard import * 2 | import numpy as np 3 | 4 | #On créé nos matrices de test 5 | a1 = [[1,2],[3,4]] 6 | a2 = [[-1, -1], [-1, -1]] 7 | 8 | b1 = [[0,1,2], [-1,-2,-3], [5, 10, 15], [100, 200, 300]] 9 | b2 = [[1,2,3], [5,10,15], [1,1,1], [0,-5, 0]] 10 | 11 | #On calcule le produit hadamard des matrices 12 | print(produit_hadamard(a1, a2)) 13 | print(produit_hadamard_2(a1, a2)) 14 | print(np.multiply(np.array(a1), np.array(a2))) 15 | print("-------------") 16 | 17 | print(produit_hadamard(b1, b2)) 18 | print(produit_hadamard_2(b1, b2)) 19 | print(np.multiply(np.array(b1), np.array(b2))) 20 | -------------------------------------------------------------------------------- /140. Produit scalaire de deux matrices/produit_scalaire.py: -------------------------------------------------------------------------------- 1 | def transpose(matrix): 2 | """Renvoie la transposée d'une matrice""" 3 | 4 | result_matrix = [] 5 | 6 | for col in range(len(matrix[0])): 7 | line_matrix = [] 8 | for line in range(len(matrix)): 9 | line_matrix.append(matrix[line][col]) 10 | result_matrix.append(line_matrix) 11 | 12 | return result_matrix 13 | 14 | 15 | 16 | def produit_scalaire(A, B): 17 | """Calcule le produit scalaire de deux matrices""" 18 | 19 | if len(A[0]) != len(B): 20 | return None 21 | 22 | result_matrix = [] 23 | for line in A: 24 | line_matrix = [] 25 | for col_B in transpose(B): 26 | result = 0 27 | for i, a in enumerate(line): 28 | result += a * col_B[i] 29 | line_matrix.append(result) 30 | result_matrix.append(line_matrix) 31 | 32 | return result_matrix -------------------------------------------------------------------------------- /140. Produit scalaire de deux matrices/test_produit_scalaire.py: -------------------------------------------------------------------------------- 1 | from produit_scalaire import * 2 | import numpy as np 3 | 4 | #On créé nos matrices 5 | a1 = [[1,2,3], [-1,-2,-3]] 6 | a2 = [[1,2], [3,4], [5,6]] 7 | 8 | b1 = [[1,2,3,4,5]] 9 | b2 = [[5], [4], [3], [2], [1]] 10 | 11 | c1 = [[1,2,3,4]] 12 | c2 = [[1,2], [3,4], [5,6]] 13 | 14 | #On calcule le résultat du produit scalaire des matrices précédentes 15 | print(produit_scalaire(a1,a2)) 16 | print(np.dot(np.array(a1), np.array(a2))) 17 | print("----------------") 18 | 19 | print(produit_scalaire(b1,b2)) 20 | print(np.dot(np.array(b1), np.array(b2))) 21 | print("----------------") 22 | 23 | print(produit_scalaire(c1,c2)) #Doit renvoyer None car les dimensions des matrices ne permettent pas le produit scalaire -------------------------------------------------------------------------------- /141. Produit cartésien de deux ensembles/produit_cartesien.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | def produit_cartesien(v1, v2): 4 | """Calcule le produit cartésien de deux vecteurs (deux listes ici)""" 5 | vecteur_final = [] 6 | for element in v1: 7 | for element_2 in v2: 8 | vecteur_final.append([element, element_2]) 9 | 10 | return vecteur_final 11 | 12 | 13 | 14 | def produit_cartesien_short(v1, v2): 15 | return [[x0, y0] for x0 in v1 for y0 in v2] 16 | 17 | 18 | 19 | def cartesien_itertools(v1, v2): 20 | """Calcule le produit cartésien en utilisant la méthode product() du module itertools""" 21 | 22 | vecteur_final = [] 23 | 24 | for element in itertools.product(v1,v2): 25 | vecteur_final.append(element) 26 | 27 | return vecteur_final -------------------------------------------------------------------------------- /141. Produit cartésien de deux ensembles/test_produit_cartesien.py: -------------------------------------------------------------------------------- 1 | from produit_cartesien import * 2 | 3 | #On créé nos vecteurs de tests 4 | v1 = [1,2,3,4] 5 | v2 = ["a", "b", "c"] 6 | v3 = ["y", "z"] 7 | 8 | #On teste la méthode produit_cartesien() 9 | print(produit_cartesien(v1, v2)) 10 | print(cartesien_itertools(v1,v2)) 11 | print(produit_cartesien_short(v1,v2)) 12 | print("------------------") 13 | 14 | print(produit_cartesien(v1, v3)) 15 | print(cartesien_itertools(v1,v3)) 16 | print(produit_cartesien_short(v1,v2)) 17 | print("------------------") 18 | 19 | print(produit_cartesien(v2, v3)) 20 | print(cartesien_itertools(v2,v3)) 21 | print(produit_cartesien_short(v1,v2)) 22 | print("------------------") -------------------------------------------------------------------------------- /142. Multiplier une matrice par un scalaire/scalaire_matrice.py: -------------------------------------------------------------------------------- 1 | def multiplier_scalaire(liste, scalaire): 2 | 3 | liste_finale = [] 4 | for element in liste: 5 | if type(element) is list: 6 | liste_finale.append(multiplier_scalaire(element, scalaire)) 7 | 8 | else: 9 | liste_finale.append(element * scalaire) 10 | 11 | return liste_finale 12 | -------------------------------------------------------------------------------- /142. Multiplier une matrice par un scalaire/test_scalaire_matrice.py: -------------------------------------------------------------------------------- 1 | from scalaire_matrice import * 2 | 3 | #On créé nos vecteurs et matrices 4 | v1 = [1,2,3,4,5] 5 | A = [[1,2,3], [4,5,6], [7,8,9]] 6 | B = [[1,2], [-1, -2]] 7 | 8 | #On teste la méthode multiplier_scalaire 9 | print(multiplier_scalaire(v1, 2)) 10 | print(multiplier_scalaire(A, -1)) 11 | print(multiplier_scalaire(B, 0)) -------------------------------------------------------------------------------- /143. Produit Kronecker de deux matrices/produit_kronecker.py: -------------------------------------------------------------------------------- 1 | def multiplier_scalaire(liste, scalaire): 2 | 3 | liste_finale = [] 4 | for element in liste: 5 | if type(element) is list: 6 | liste_finale.append(multiplier_scalaire(element, scalaire)) 7 | 8 | else: 9 | liste_finale.append(element * scalaire) 10 | 11 | return liste_finale 12 | 13 | 14 | 15 | def produit_kronecker(A, B): 16 | """Calcule le produit de Kronecker entre la matrice A et la matrice B""" 17 | 18 | final_matrix = [] 19 | 20 | for line in A: 21 | for line_B in B: 22 | line_matrix = [] 23 | for col in line: 24 | for col_b in line_B: 25 | line_matrix.append(col * col_b) 26 | final_matrix.append(line_matrix) 27 | 28 | return final_matrix 29 | 30 | -------------------------------------------------------------------------------- /143. Produit Kronecker de deux matrices/test_produit_kronecker.py: -------------------------------------------------------------------------------- 1 | from produit_kronecker import * 2 | import numpy as np 3 | 4 | #On créé nos matrices de test 5 | A = [[1,2,3], [4,5,6], [7,8,9]] 6 | B = [[1,2], [3,4]] 7 | C = [[-1, -2, -3]] 8 | 9 | 10 | #On teste la méthode produit_kronecker() 11 | print(produit_kronecker(A,B)) 12 | print(np.kron(np.array(A), np.array(B))) 13 | print("------------") 14 | 15 | print(produit_kronecker(B,A)) 16 | print(np.kron(np.array(B), np.array(A))) 17 | print("------------") 18 | 19 | print(produit_kronecker(C,A)) 20 | print(np.kron(np.array(C), np.array(A))) 21 | print("------------") -------------------------------------------------------------------------------- /144. Calculer le déterminant d'une matrice carrée d'ordre 2/determinant_2.py: -------------------------------------------------------------------------------- 1 | def determinant_2(M): 2 | """Calcule le déterminant d'une matrice carrée d'ordre 2""" 3 | 4 | return M[0][0] * M[1][1] - M[0][1] * M[1][0] -------------------------------------------------------------------------------- /144. Calculer le déterminant d'une matrice carrée d'ordre 2/test_determinant_2.py: -------------------------------------------------------------------------------- 1 | from determinant_2 import * 2 | 3 | #On créé nos matrices de test 4 | A = [[1,1], [1,1]] 5 | B = [[2,1], [3,2]] 6 | C = [[10,1], [0,5]] 7 | 8 | #On teste la méthode determinant_2() 9 | print(determinant_2(A)) 10 | print(determinant_2(B)) 11 | print(determinant_2(C)) -------------------------------------------------------------------------------- /145. Calculer le déterminant d'une matrice carrée d'ordre 3/determinant_3.py: -------------------------------------------------------------------------------- 1 | def determinant_3(M): 2 | """Calcule le déterminant d'une matrice carrée d'ordre 3""" 3 | 4 | aei = M[0][0] * M[1][1] * M[2][2] 5 | bfg = M[0][1] * M[1][2] * M[2][0] 6 | cdh = M[0][2] * M[1][0] * M[2][1] 7 | ceg = M[0][2] * M[1][1] * M[2][0] 8 | bdi = M[0][1] * M[1][0] * M[2][2] 9 | afh = M[0][0] * M[1][2] * M[2][1] 10 | 11 | return aei + bfg + cdh - ceg - bdi - afh -------------------------------------------------------------------------------- /145. Calculer le déterminant d'une matrice carrée d'ordre 3/test_determinant_3.py: -------------------------------------------------------------------------------- 1 | from determinant_3 import * 2 | 3 | #On créé nos matrices de test 4 | A = [[1,2,3], [4,5,6], [7,8,9]] 5 | B = [[3,0,2], [-1,1,0], [5,2,3]] 6 | C = [[2, 1, 3], [1,0,2], [2,0,-2]] 7 | D = [[1,2,3], [0,4,5], [2,1,9]] 8 | #On teste la méthode determinant_3() 9 | print(determinant_3(A)) 10 | print(determinant_3(B)) 11 | print(determinant_3(C)) 12 | print(determinant_3(D)) 13 | -------------------------------------------------------------------------------- /146. Calculer la trace d'une matrice/test_trace.py: -------------------------------------------------------------------------------- 1 | from trace_matrice import trace 2 | import numpy as np 3 | 4 | #On créé nos matrices de test 5 | A = [[1,2,3], [4,5,6], [7,8,9]] 6 | B = [[0,1], [2,3]] 7 | I = [[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]] 8 | C = [[1,2,3], [4,5,6]] 9 | D = [[0,1], [4,6], [10,11]] 10 | E = [[1,2], [3,4], [5,6]] 11 | 12 | #On teste notre méthode trace() 13 | print("Trace de A :", trace(A)) 14 | print("Trace de A :", np.trace(np.array(A))) 15 | print("Trace de B :", trace(B)) 16 | print("Trace de B :", np.trace(np.array(B))) 17 | print("Trace de I :", trace(I)) 18 | print("Trace de I :", np.trace(np.array(I))) 19 | print("Trace de C :", trace(C)) 20 | print("Trace de C :", np.trace(np.array(C))) 21 | print("Trace de D :", trace(D)) 22 | print("Trace de D :", np.trace(np.array(D))) 23 | print("Trace de E :", trace(E)) 24 | print("Trace de E :", np.trace(np.array(E))) -------------------------------------------------------------------------------- /146. Calculer la trace d'une matrice/trace_matrice.py: -------------------------------------------------------------------------------- 1 | def trace(M): 2 | """Renvoie la trace d'une matrice""" 3 | 4 | T = 0 5 | 6 | if len(M) < len(M[0]): 7 | calc_range = len(M) 8 | else: 9 | calc_range = len(M[0]) 10 | 11 | for i in range(calc_range): 12 | T += M[i][i] 13 | 14 | return T -------------------------------------------------------------------------------- /147. Calculer le permanent d'une matrice carrée d'ordre 2/permanent_2.py: -------------------------------------------------------------------------------- 1 | def permanent_2(M): 2 | """Calcule le permanent d'une matrice carrée d'ordre 2""" 3 | 4 | return M[0][0] * M[1][1] + M[0][1] * M[1][0] -------------------------------------------------------------------------------- /147. Calculer le permanent d'une matrice carrée d'ordre 2/test_permanent_2.py: -------------------------------------------------------------------------------- 1 | from permanent_2 import * 2 | 3 | #On créé nos matrices de test 4 | A = [[1,1], [1,1]] 5 | B = [[2,1], [3,2]] 6 | C = [[10,1], [0,5]] 7 | 8 | #On teste la méthode permanent_2() 9 | print(permanent_2(A)) 10 | print(permanent_2(B)) 11 | print(permanent_2(C)) -------------------------------------------------------------------------------- /148. Calculer le permanent d'une matrice carrée d'ordre 3/permanent_3.py: -------------------------------------------------------------------------------- 1 | def permanent_3(M): 2 | """Calcule le permanent d'une matrice carrée d'ordre 3""" 3 | 4 | aei = M[0][0] * M[1][1] * M[2][2] 5 | bfg = M[0][1] * M[1][2] * M[2][0] 6 | cdh = M[0][2] * M[1][0] * M[2][1] 7 | ceg = M[0][2] * M[1][1] * M[2][0] 8 | bdi = M[0][1] * M[1][0] * M[2][2] 9 | afh = M[0][0] * M[1][2] * M[2][1] 10 | 11 | return aei + bfg + cdh + ceg + bdi + afh -------------------------------------------------------------------------------- /148. Calculer le permanent d'une matrice carrée d'ordre 3/test_permanent_3.py: -------------------------------------------------------------------------------- 1 | from permanent_3 import * 2 | 3 | #On créé nos matrices de test 4 | A = [[1,2,3], [4,5,6], [7,8,9]] 5 | B = [[3,0,2], [-1,1,0], [5,2,3]] 6 | C = [[2, 1, 3], [1,0,2], [2,0,-2]] 7 | 8 | #On teste la méthode permanent_3() 9 | print(permanent_3(A)) 10 | print(permanent_3(B)) 11 | print(permanent_3(C)) -------------------------------------------------------------------------------- /149. Matrice de Toeplitz/test_toeplitz.py: -------------------------------------------------------------------------------- 1 | from toeplitz import is_toeplitz 2 | 3 | def print_matrix(matrix): 4 | for row in matrix: 5 | print(row) 6 | 7 | print("------------------------") 8 | matrix = [[1,2,3], 9 | [3,1,2], 10 | [4,3,1] 11 | ] 12 | print_matrix(matrix) 13 | print(is_toeplitz(matrix)) 14 | 15 | print("------------------------") 16 | matrix = [[1,2], 17 | [3,1], 18 | [16,3], 19 | [8,16], 20 | [7,8] 21 | ] 22 | print_matrix(matrix) 23 | print(is_toeplitz(matrix)) 24 | 25 | print("------------------------") 26 | matrix = [[1,2,3,4,5,6,7,8,9], 27 | [10,1,2,3,4,5,6,7,8] 28 | ] 29 | print_matrix(matrix) 30 | print(is_toeplitz(matrix)) 31 | 32 | print("------------------------") 33 | matrix = [[1,2,3], 34 | [4,5,6], 35 | [7,8,9] 36 | ] 37 | print_matrix(matrix) 38 | print(is_toeplitz(matrix)) 39 | -------------------------------------------------------------------------------- /149. Matrice de Toeplitz/toeplitz.py: -------------------------------------------------------------------------------- 1 | def is_toeplitz(matrix): 2 | """Renvoie True si la matrice envoyée en paramètre est une matrice de Toeplitz.""" 3 | 4 | rows, cols = len(matrix), len(matrix[0]) 5 | 6 | for row in range(rows - 1): 7 | for col in range(cols - 1): 8 | if matrix[row][col] != matrix[row+1][col+1]: 9 | return False 10 | 11 | return True 12 | -------------------------------------------------------------------------------- /150. Aplatir des listes imbriquées/flatten.py: -------------------------------------------------------------------------------- 1 | def flatten_recursif(liste): 2 | """Applatit une liste en utilisant la récursivité""" 3 | 4 | final_liste = [] 5 | for element in liste: 6 | if type(element) is list: 7 | final_liste += flatten_recursif(element) 8 | else: 9 | final_liste.append(element) 10 | 11 | return final_liste 12 | 13 | 14 | 15 | def flatten_recursif_short(liste): 16 | """Applatit une liste en utilisant la récursivité : code obtenu sur http://www.rosettacode.org/wiki/Flatten_a_list#Python""" 17 | 18 | return sum(([x] if not isinstance(x,list) else flatten_recursif_short(x) for x in liste), []) 19 | 20 | 21 | 22 | def flatten(liste): 23 | """Applatit une liste de listes de profondeur 2 avec une méthode itérative.""" 24 | 25 | return [element for sousliste in liste for element in sousliste] -------------------------------------------------------------------------------- /150. Aplatir des listes imbriquées/test_flatten.py: -------------------------------------------------------------------------------- 1 | from flatten import * 2 | 3 | #On créé nos listes 4 | a = [1,2,3,4,5,6,7,8,9,10] 5 | b = [1, [2,3], [4, [5,6, [7,8,9]]], 10] 6 | c = [[[[[[[[1,2,3,4], [5,[6,7,8]]]]]]]], 9, 10] 7 | d = [[], [1,2,3], [[]], 4,5,6,[[[7,8]]], 9, [10]] 8 | 9 | #Test des méthodes 10 | print(flatten_recursif(a)) 11 | print(flatten_recursif_short(a)) 12 | print(flatten_recursif(b)) 13 | print(flatten_recursif_short(b)) 14 | print(flatten_recursif(c)) 15 | print(flatten_recursif_short(c)) 16 | print(flatten_recursif(d)) 17 | print(flatten_recursif_short(d)) 18 | 19 | #Test de flatten 20 | e = [[1,2,3], [4,5,6], [7,8,9,10]] 21 | f = [[1,2],[3,4],[5,6], [7,8], [9,10]] 22 | print(flatten(e)) 23 | print(flatten(f)) -------------------------------------------------------------------------------- /151. Les piles/pile.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Pile: 4 | """Structure de données respectant le modèle LIFO (dernier entré, premier sorti).""" 5 | 6 | def __init__(self, maxSize=None): 7 | self._items = [] 8 | self.MAX_SIZE = sys.maxint if maxSize == None else maxSize 9 | 10 | 11 | 12 | def push(self, item): 13 | """Ajoute un ou plusieurs éléments sur la pile.""" 14 | 15 | if type(item) is list: 16 | for it in item: 17 | if len(self._items) < self.MAX_SIZE: 18 | self._items.append(it) 19 | else: 20 | break 21 | else: 22 | if len(self._items) < self.MAX_SIZE: 23 | self._items.append(item) 24 | else: 25 | raise IndexError("The stack is already full") 26 | 27 | 28 | 29 | def next_item_to_pop(self): 30 | """Renvoie le prochain élément qui sera retiré de la pile si on fait appel à la méthode pop().""" 31 | 32 | self._items[-1] 33 | 34 | 35 | 36 | def pop(self): 37 | """Retire le dernier élément qui a été ajouté à la pile.""" 38 | 39 | if len(self._items) <= 0: 40 | raise IndexError("Can't pop from empty stack") 41 | self._items.pop(-1) 42 | 43 | 44 | 45 | def is_empty(self): 46 | """Renvoie True si la pile est vide, sinon renvoie False.""" 47 | 48 | return len(self._items) == 0 49 | 50 | 51 | 52 | def length(self): 53 | """Renvoie la longueur de la pile.""" 54 | 55 | return len(self._items) 56 | 57 | 58 | 59 | def __str__(self): 60 | """Renvoie la pile sous forme de chaîne de caractères.""" 61 | 62 | return str(self._items) 63 | 64 | 65 | 66 | def min(self): 67 | """Renvoie la valeur minimum de la pile.""" 68 | 69 | return min(self._items) 70 | 71 | 72 | 73 | def max(self): 74 | """Renvoie la valeur maximum de la pile.""" 75 | 76 | return max(self._items) 77 | 78 | 79 | 80 | def find(self, item): 81 | """Renvoie l'indice de l'élément recherché (item) dans la pile.""" 82 | 83 | return self._items.index(item) 84 | 85 | 86 | 87 | def reset(self): 88 | """Réinitialise la pile.""" 89 | 90 | self._items = [] -------------------------------------------------------------------------------- /151. Les piles/test_pile.py: -------------------------------------------------------------------------------- 1 | from pile import Pile 2 | 3 | p1 = Pile() 4 | p1.push(1) 5 | p1.push(2) 6 | p1.push(3) 7 | print("Min :", p1.min()) 8 | print("Max :", p1.max()) 9 | print("Find 2 :", p1.find(2)) 10 | print("Longueur :", p1.length()) 11 | print("Taille maximale : ", p1.MAX_SIZE) 12 | print(p1) 13 | p1.pop() 14 | print(p1) 15 | p1.reset() 16 | print(p1) 17 | print("-------------------") 18 | p2 = Pile(5) 19 | p2.push(1) 20 | p2.push(2) 21 | p2.push([3,4,5]) 22 | p2.push(6) 23 | -------------------------------------------------------------------------------- /152. Les files/queue.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Queue: 4 | """Structure de données respectant le modèle FIFO (premier entré, premier sorti).""" 5 | 6 | def __init__(self, max_size = None): 7 | self._items = [] 8 | self.MAX_SIZE = sys.maxint if max_size == None else max_size 9 | 10 | 11 | 12 | def push(self, item): 13 | """Ajoute un ou plusieurs éléments dans la file.""" 14 | 15 | if type(item) is list: 16 | for it in item: 17 | if len(self._items) < self.MAX_SIZE: 18 | self._items.append(it) 19 | else: 20 | break 21 | 22 | else: 23 | if len(self._items) < self.MAX_SIZE: 24 | self._items.append(item) 25 | else: 26 | raise IndexError("The queue is already full") 27 | 28 | 29 | 30 | def pop(self): 31 | """Retire le premier élément de la file.""" 32 | 33 | self._items.pop(0) 34 | 35 | 36 | 37 | def next_item_to_pop(self): 38 | """Renvoie le prochain élément qui sera retiré de la file si on fait appel à la méthode pop().""" 39 | 40 | return self._items[0] 41 | 42 | 43 | 44 | def is_empty(self): 45 | """Renvoie True si la file est vide, sinon renvoie False.""" 46 | 47 | return len(self._items) == 0 48 | 49 | 50 | 51 | def length(self): 52 | """Renvoie la longueur de la file.""" 53 | 54 | return len(self._items) 55 | 56 | 57 | 58 | def __str__(self): 59 | """Renvoie la file sous forme de chaîne de caractères.""" 60 | 61 | return str(self._items) 62 | 63 | 64 | 65 | def min(self): 66 | """Renvoie la valeur minimum de la file.""" 67 | 68 | return min(self._items) 69 | 70 | 71 | 72 | def max(self): 73 | """Renvoie la valeur maximum de la file.""" 74 | 75 | return max(self._items) 76 | 77 | 78 | 79 | def find(self, item): 80 | """Renvoie l'indice de l'élément recherché (item) dans la file.""" 81 | 82 | return self._items.index(item) 83 | 84 | 85 | 86 | def reset(self): 87 | """Réinitialise la file.""" 88 | 89 | self._items = [] -------------------------------------------------------------------------------- /152. Les files/test_file.py: -------------------------------------------------------------------------------- 1 | from queue import Queue 2 | 3 | f1 = Queue(10) 4 | 5 | #On ajoute 10 éléments à la file : 1,2,3,4,5,6,7,8,9,10 6 | for i in range(10): 7 | f1.push(i) 8 | print(f1) 9 | 10 | #On supprime 5 éléments de la file. 11 | for i in range(5): 12 | f1.pop() 13 | print(f1) 14 | 15 | print("Valeur maximale :", f1.max()) 16 | print("Valeur minimale :", f1.min()) 17 | print("Longueur de la file :", f1.length()) 18 | print("Prochain élément à être supprimé :", f1.next_item_to_pop()) 19 | print("Est vide?", f1.is_empty()) 20 | print("Indice de l'élément 8 :", f1.find(8)) 21 | print("---- Réinitialisation de la file ----") 22 | f1.reset() 23 | print(f1) 24 | print("Est vide?", f1.is_empty()) -------------------------------------------------------------------------------- /153. Les listes chaînées/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None -------------------------------------------------------------------------------- /153. Les listes chaînées/test_linkedlist.py: -------------------------------------------------------------------------------- 1 | from linkedlist import LinkedList 2 | 3 | l1 = LinkedList() 4 | print("Est vide?", l1.is_empty()) 5 | 6 | #On insère 10 éléments dans la liste chaînée 7 | for i in range(10): 8 | l1.add(i) 9 | 10 | l1.traverse_list() 11 | l1.display_first_last() 12 | print() 13 | 14 | print("Longueur :", l1.length()) 15 | print("Est vide?", l1.is_empty()) 16 | print("Noeud à l'indice 5 :", l1.get_node(5)) 17 | 18 | print() 19 | print("On ajoute la valeur 50 à l'indice 5") 20 | l1.insert(5, 50) 21 | l1.traverse_list() 22 | l1.display_first_last() 23 | 24 | print() 25 | print("On retire le 50") 26 | l1.remove(50) 27 | l1.traverse_list() 28 | l1.display_first_last() 29 | 30 | print() 31 | print("On ajoute le 11 et le 10") 32 | l1.insert_after(9, 11) 33 | l1.insert_after(9, 10) 34 | l1.traverse_list() 35 | l1.display_first_last() 36 | 37 | print() 38 | print("On insère un 10 après le 5") 39 | l1.insert_after(5, 10) 40 | l1.traverse_list() 41 | l1.display_first_last() 42 | 43 | print() 44 | print("On retire le 10 après le 5") 45 | l1.pop(6) 46 | l1.traverse_list() 47 | l1.display_first_last() 48 | 49 | print() 50 | print("On retire le 9, le 10 et le 11") 51 | l1.remove(9) 52 | l1.remove_last() 53 | l1.remove_last() 54 | l1.traverse_list() 55 | l1.display_first_last() 56 | 57 | print() 58 | print("On retire le 0") 59 | l1.remove(0) 60 | l1.traverse_list() 61 | l1.display_first_last() 62 | 63 | print() 64 | print("On retire tous les éléments allant de 1 à 5 inclus.") 65 | for i in range(1, 6): 66 | l1.remove(i) 67 | l1.traverse_list() 68 | l1.display_first_last() 69 | 70 | print() 71 | print("On retire le premier élément") 72 | l1.remove_first() 73 | l1.traverse_list() 74 | l1.display_first_last() 75 | 76 | print() 77 | print("On retire le premier élément") 78 | l1.pop(0) 79 | l1.traverse_list() 80 | l1.display_first_last() 81 | 82 | print() 83 | print("On retire le premier élément") 84 | l1.pop(0) 85 | l1.traverse_list() 86 | l1.display_first_last() -------------------------------------------------------------------------------- /154. Inverser une liste chaînée/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None -------------------------------------------------------------------------------- /154. Inverser une liste chaînée/test_inverse_linkedlist.py: -------------------------------------------------------------------------------- 1 | from linkedlist import LinkedList 2 | 3 | l = LinkedList() 4 | 5 | #On ajoute 10 éléments à notre liste chaînée 6 | for i in range(1, 10): 7 | l.add(i) 8 | 9 | print("---- Liste chaînée 1 ----") 10 | l.traverse_list() 11 | print("Inverse de la liste") 12 | l.inverse() 13 | l.traverse_list() 14 | 15 | l2 = LinkedList() 16 | l2.add(1) 17 | l2.add(2) 18 | print("---- Liste chaînée 2 ----") 19 | l2.traverse_list() 20 | l2.inverse() 21 | l2.traverse_list() 22 | 23 | l3 = LinkedList() 24 | l3.add(1) 25 | print("---- Liste chaînée 3 ----") 26 | l3.traverse_list() 27 | l3.inverse() 28 | l3.traverse_list() -------------------------------------------------------------------------------- /155. Les listes chaînées doubles/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None 7 | self.previous = None -------------------------------------------------------------------------------- /155. Les listes chaînées doubles/test_doublylinkedlist.py: -------------------------------------------------------------------------------- 1 | from doublylinkedlist import DoublyLinkedList 2 | 3 | dl = DoublyLinkedList() 4 | 5 | #Ajout de 2,3,4 6 | print("Ajout de 2,3,4") 7 | dl.add(2) 8 | dl.add(3) 9 | dl.add(4) 10 | dl.traverse_list() 11 | dl.display_first_last() 12 | print() 13 | 14 | #Ajout de 2 au début, 6 à la fin, puis on retire le 6 et on retire le 2 au début 15 | print("Ajout de 2 au début, 6 à la fin") 16 | dl.add_first(2) 17 | dl.add(6) 18 | dl.traverse_list() 19 | dl.display_first_last() 20 | print() 21 | 22 | print("On retire le 6 et le 2 au début") 23 | dl.remove_last() 24 | dl.remove_first() 25 | dl.traverse_list() 26 | dl.display_first_last() 27 | print() 28 | 29 | #On ajoute le 1 au début, le 5 à la fin 30 | print("On ajoute le 1 au début, le 5 à la fin") 31 | dl.add_first(1) 32 | dl.add(5) 33 | dl.traverse_list() 34 | dl.display_first_last() 35 | print() 36 | 37 | #On ajoute le 6, puis le 8, puis le 10 38 | print("On ajoute le 6, puis le 8, puis le 10") 39 | dl.add(6) 40 | dl.add(8) 41 | dl.add(10) 42 | dl.traverse_list() 43 | dl.display_first_last() 44 | print() 45 | 46 | #On insère le 7 à l'indice 6 et le 9 à l'indice 8 47 | print("On insère le 7 à l'indice 6 et le 9 à l'indice 8") 48 | dl.insert(6, 7) 49 | dl.traverse_list() 50 | dl.insert_after(7, 9) 51 | dl.traverse_list() 52 | dl.display_first_last() 53 | print() 54 | 55 | 56 | print("Noeud à l'indice 5 :", dl.get_node(5)._item) 57 | print("Noeud à l'indice 0 :", dl.get_node(0)._item) 58 | print("Noeud à l'indice 9 :", dl.get_node(9)._item) 59 | print("Longueur de la liste chaînée double :", dl.length()) 60 | print("Est vide?", dl.is_empty()) 61 | dl.display_first_last() 62 | 63 | print() 64 | print("On retire le 10") 65 | dl.remove(10) 66 | dl.traverse_list() 67 | dl.display_first_last() 68 | print() -------------------------------------------------------------------------------- /156. Inverser une liste doublement chaînée/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None 7 | self.previous = None -------------------------------------------------------------------------------- /156. Inverser une liste doublement chaînée/test_inverse_doublylinkedlist.py: -------------------------------------------------------------------------------- 1 | from inverse_doublylinkedlist import DoublyLinkedList 2 | 3 | dl = DoublyLinkedList() 4 | 5 | print("Inversion de la liste 1,2,3,4") 6 | dl.add(1) 7 | dl.add(2) 8 | dl.add(3) 9 | dl.add(4) 10 | dl.traverse_list() 11 | dl.inverse() 12 | dl.traverse_list() 13 | 14 | print("Inverse d'une liste avec un seul élément") 15 | dl2 = DoublyLinkedList() 16 | dl2.add(2) 17 | dl2.inverse() 18 | dl2.traverse_list() -------------------------------------------------------------------------------- /157. Renvoyer le noeud au milieu d'une liste chaînée/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None -------------------------------------------------------------------------------- /157. Renvoyer le noeud au milieu d'une liste chaînée/test_linkedlist.py: -------------------------------------------------------------------------------- 1 | from linkedlist import LinkedList 2 | 3 | l = LinkedList() 4 | 5 | print("Renvoie le noeud central d'une liste chaînée de longueur 5 (longueur impaire)") 6 | l.add(1) 7 | l.add(2) 8 | l.add(3) 9 | l.add(4) 10 | l.add(5) 11 | l.traverse_list() 12 | print(l.get_middle_node()._item) 13 | print() 14 | 15 | print("Renvoie le noeud central d'une liste chaînée de taille 20 (longueur paire)") 16 | l1 = LinkedList() 17 | for i in range(1, 21): 18 | l1.add(i) 19 | l1.traverse_list() 20 | print(l1.get_middle_node()._item) 21 | 22 | print("Renvoie le noeud central d'une liste chaînée de longueur 1") 23 | l2 = LinkedList() 24 | l2.add(5) 25 | l2.traverse_list() 26 | print(l2.get_middle_node()._item) -------------------------------------------------------------------------------- /158. Echanger les nœuds d'une liste chaînée par pair/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None -------------------------------------------------------------------------------- /158. Echanger les nœuds d'une liste chaînée par pair/test_linkedlist.py: -------------------------------------------------------------------------------- 1 | from linkedlist import LinkedList 2 | 3 | l1 = LinkedList() 4 | 5 | print("On créé une première liste chaînée de 20 éléments et on échange ses pairs de valeurs") 6 | for i in range(1, 21): 7 | l1.add(i) 8 | 9 | l1.traverse_list() 10 | l1.swap_pairs() 11 | l1.traverse_list() 12 | l1.display_first_last() 13 | print() 14 | 15 | print("On créé une deuxième liste chaînée avec un nombre impair d'élément") 16 | l2 = LinkedList() 17 | for i in range(1, 12): 18 | l2.add(i) 19 | 20 | l2.traverse_list() 21 | l2.swap_pairs() 22 | l2.traverse_list() 23 | l2.display_first_last() 24 | print() 25 | 26 | print("Swap sur une liste chaînée de taille 1") 27 | l3 = LinkedList() 28 | l3.add(1) 29 | l3.traverse_list() 30 | l3.swap_pairs() 31 | l3.traverse_list() 32 | l3.display_first_last() 33 | print() 34 | 35 | print("Swap sur une liste chaînée de taille 2") 36 | l4 = LinkedList() 37 | l4.add(1) 38 | l4.add(2) 39 | l4.traverse_list() 40 | l4.swap_pairs() 41 | l4.traverse_list() 42 | l4.display_first_last() 43 | print() -------------------------------------------------------------------------------- /159. Déterminer si une liste chaînée est cyclique/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None -------------------------------------------------------------------------------- /160. Donner le noeud où commence le cycle d'une liste chaînée cyclique/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None -------------------------------------------------------------------------------- /161. Partitionner une liste chaînée/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None -------------------------------------------------------------------------------- /161. Partitionner une liste chaînée/test_partition.py: -------------------------------------------------------------------------------- 1 | from linkedlist import LinkedList 2 | import random 3 | 4 | l1 = LinkedList() 5 | 6 | print("On créé la liste chaînée : 7, 11, 9, 50, 49, 10, 2") 7 | l1.add(7) 8 | l1.add(11) 9 | l1.add(9) 10 | l1.add(50) 11 | l1.add(49) 12 | l1.add(10) 13 | l1.add(2) 14 | l1.traverse_list() 15 | 16 | print("On la partitionne avec la valeur x = 10") 17 | l1_partition = l1.partition(10) 18 | l1_partition.traverse_list() 19 | print() 20 | 21 | l2 = LinkedList() 22 | print("On créé une liste chaînée avec des valeurs allant de 1 à 20 mélangées") 23 | shuffled_range = [x for x in range(1,21)] 24 | random.shuffle(shuffled_range) 25 | 26 | for i in shuffled_range: 27 | l2.add(i) 28 | l2.traverse_list() 29 | 30 | print("On la partitionne avec la valeur x = 12") 31 | l2_partition = l2.partition(12) 32 | l2_partition.traverse_list() 33 | 34 | 35 | -------------------------------------------------------------------------------- /162. Déterminer si une liste chaînée simple est palindromique/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None -------------------------------------------------------------------------------- /162. Déterminer si une liste chaînée simple est palindromique/test_is_palindrome.py: -------------------------------------------------------------------------------- 1 | from linkedlist import LinkedList 2 | 3 | l1 = LinkedList() 4 | l1.add(1) 5 | l1.add(3) 6 | l1.add(5) 7 | l1.add(3) 8 | l1.add(1) 9 | print("Test si la liste chaînée simple [1,3,5,3,1] est palindromique.") 10 | l1.traverse_list() 11 | print("Is palindrome?", l1.is_palindrome()) 12 | print() 13 | 14 | l2 = LinkedList() 15 | l2.add(1) 16 | l2.add(3) 17 | l2.add(5) 18 | l2.add(5) 19 | l2.add(3) 20 | l2.add(1) 21 | print("Test si la liste chaînée simple [1,3,5,5,3,1] est palindromique.") 22 | l2.traverse_list() 23 | print("Is palindrome?", l2.is_palindrome()) 24 | print() 25 | 26 | l3 = LinkedList() 27 | l3.add(1) 28 | l3.add(3) 29 | l3.add(5) 30 | l3.add(5) 31 | l3.add(3) 32 | l3.add(0) 33 | print("Test si la liste chaînée simple [1,3,5,5,3,0] est palindromique.") 34 | l3.traverse_list() 35 | print("Is palindrome?", l3.is_palindrome()) 36 | print() 37 | -------------------------------------------------------------------------------- /163. Déterminer si une liste doublement chaînée est palindromique/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None 7 | self.previous = None -------------------------------------------------------------------------------- /163. Déterminer si une liste doublement chaînée est palindromique/test_palindrome_doublylinkedlist.py: -------------------------------------------------------------------------------- 1 | from doublylinkedlist import DoublyLinkedList 2 | 3 | print("On va tester si la liste doublement chaînée [1,3,5,3,1] est palindromique.") 4 | dl1 = DoublyLinkedList() 5 | dl1.add(1) 6 | dl1.add(3) 7 | dl1.add(5) 8 | dl1.add(3) 9 | dl1.add(1) 10 | dl1.traverse_list() 11 | print("Palindrome?", dl1.is_palindrome()) 12 | print() 13 | 14 | print("On va tester si la liste doublement chaînée [1,3,5,5,3,1] est palindromique.") 15 | dl2 = DoublyLinkedList() 16 | dl2.add(1) 17 | dl2.add(3) 18 | dl2.add(5) 19 | dl2.add(5) 20 | dl2.add(3) 21 | dl2.add(1) 22 | dl2.traverse_list() 23 | print("Palindrome?", dl2.is_palindrome()) 24 | print() 25 | 26 | print("On va tester si la liste doublement chaînée [1,3,5,5,3,0] est palindromique.") 27 | dl3 = DoublyLinkedList() 28 | dl3.add(1) 29 | dl3.add(3) 30 | dl3.add(5) 31 | dl3.add(5) 32 | dl3.add(3) 33 | dl3.add(0) 34 | dl3.traverse_list() 35 | print("Palindrome?", dl3.is_palindrome()) 36 | print() 37 | 38 | print("On va tester si la liste doublement chaînée [1,3,5,3,0] est palindromique.") 39 | dl4 = DoublyLinkedList() 40 | dl4.add(1) 41 | dl4.add(3) 42 | dl4.add(5) 43 | dl4.add(3) 44 | dl4.add(0) 45 | dl4.traverse_list() 46 | print("Palindrome?", dl4.is_palindrome()) 47 | print() 48 | -------------------------------------------------------------------------------- /164. Additionner deux nombres formés par une liste chaînée/addition_number_linkedlist.py: -------------------------------------------------------------------------------- 1 | from node import Node 2 | 3 | def addition_linkedlist(n1, n2): 4 | """Additionne deux nombres formés par des listes chaînées. Retourne le premier noeud 5 | de la liste chaînée qui forme le résultat de l'addition. 6 | :type n1: Node() 7 | :type n2: Node() 8 | :rtype: Node() 9 | 10 | Leetcode 445 de l'application Android Leetcode Python""" 11 | 12 | 13 | num1, num2 = 0, 0 14 | 15 | node = n1 16 | while node: 17 | num1 = num1 * 10 + node._item 18 | node = node.next 19 | node = n2 20 | while node: 21 | num2 = num2 * 10 + node._item 22 | node = node.next 23 | 24 | total = num1 + num2 25 | if total == 0: # return single node with zero 26 | return Node(0) 27 | result = None 28 | 29 | while total: 30 | total, digit = divmod(total, 10) 31 | new_node = Node(digit) 32 | new_node.next = result # make digit start of result 33 | result = new_node 34 | 35 | return result -------------------------------------------------------------------------------- /164. Additionner deux nombres formés par une liste chaînée/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None -------------------------------------------------------------------------------- /164. Additionner deux nombres formés par une liste chaînée/test_addition_number_linked_list.py: -------------------------------------------------------------------------------- 1 | from linkedlist import LinkedList 2 | from addition_number_linkedlist import addition_linkedlist 3 | 4 | print("Addition de 1000 et 671") 5 | l1 = LinkedList() 6 | l2 = LinkedList() 7 | l1.add(1) 8 | l1.add(0) 9 | l1.add(0) 10 | l1.add(0) 11 | l2.add(6) 12 | l2.add(7) 13 | l2.add(1) 14 | l1.traverse_list() 15 | l2.traverse_list() 16 | node = addition_linkedlist(l1.first, l2.first) 17 | while node: 18 | print(node._item, end="") 19 | node = node.next 20 | print() 21 | 22 | print("Addition de 11111 et 99999") 23 | l1 = LinkedList() 24 | l2 = LinkedList() 25 | l1.add(1) 26 | l1.add(1) 27 | l1.add(1) 28 | l1.add(1) 29 | l1.add(1) 30 | l2.add(9) 31 | l2.add(9) 32 | l2.add(9) 33 | l2.add(9) 34 | l2.add(9) 35 | l1.traverse_list() 36 | l2.traverse_list() 37 | node = addition_linkedlist(l1.first, l2.first) 38 | while node: 39 | print(node._item, end="") 40 | node = node.next 41 | print() -------------------------------------------------------------------------------- /165. Convertir un nombre binaire contenue dans une liste chaînée en un nombre entier/convert_binary_linkedlist.py: -------------------------------------------------------------------------------- 1 | from linkedlist import LinkedList 2 | 3 | def get_decimal_value(liste): 4 | """ 5 | Renvoie la valeur en base décimale d'un nombre binaire représenté par une liste chaînée. 6 | :type first: ListNode 7 | :rtype: int 8 | 9 | Leetcode 1290 de l'application Android Leetcode Python 10 | """ 11 | result = 0 12 | first = liste.first 13 | 14 | while first: 15 | result = result * 2 + first._item 16 | first = first.next 17 | 18 | return result -------------------------------------------------------------------------------- /165. Convertir un nombre binaire contenue dans une liste chaînée en un nombre entier/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | """Noeud d'une liste chaînée""" 3 | 4 | def __init__(self, data): 5 | self._item = data 6 | self.next = None -------------------------------------------------------------------------------- /165. Convertir un nombre binaire contenue dans une liste chaînée en un nombre entier/test_convert_binary_linkedlist.py: -------------------------------------------------------------------------------- 1 | from convert_binary_linkedlist import get_decimal_value 2 | from linkedlist import LinkedList 3 | 4 | print("Conversion de 101 en base décimale") 5 | l1 = LinkedList() 6 | l1.add(1) 7 | l1.add(0) 8 | l1.add(1) 9 | l1.traverse_list() 10 | print("=> ", get_decimal_value(l1)) 11 | print() 12 | 13 | print("Conversion de 1010 en base décimale") 14 | l2 = LinkedList() 15 | l2.add(1) 16 | l2.add(0) 17 | l2.add(1) 18 | l2.add(0) 19 | l2.traverse_list() 20 | print("=> ", get_decimal_value(l2)) 21 | print() 22 | 23 | print("Conversion de 1 en base décimale") 24 | l3 = LinkedList() 25 | l3.add(1) 26 | l3.traverse_list() 27 | print("=> ", get_decimal_value(l3)) 28 | print() 29 | 30 | print("Conversion de 0 en base décimale") 31 | l4 = LinkedList() 32 | l4.add(0) 33 | l4.traverse_list() 34 | print("=> ", get_decimal_value(l4)) 35 | print() 36 | 37 | -------------------------------------------------------------------------------- /Exercices d'algorithmie.ods: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/foxxpy/Algorithmie/098b9f339400ca642b698d53df953ceb1fa9fe67/Exercices d'algorithmie.ods --------------------------------------------------------------------------------