From 5c5332573dee72b46a619c8080c2fdeeb9336adf Mon Sep 17 00:00:00 2001
From: Romain Vuillemot <romain.vuillemot@gmail.com>
Date: Tue, 2 Feb 2021 11:40:11 +0100
Subject: [PATCH] =?UTF-8?q?Mise=20=C3=A0=20jour=20code=20exercices?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 TD01/code/addition.py                   |  2 +-
 TD01/code/comprehension-list-filter.py  |  8 +++
 TD01/code/exceptions.py                 | 33 ++++++++++
 TD01/code/format.py                     | 87 +++++++++++++++++++++++++
 TD01/code/listes.py                     |  5 ++
 TD01/code/premier.py                    | 30 +++++++++
 TD01/code/recherche-dichotomie-place.py | 27 ++++++++
 TD01/code/recherche-dichotomie.py       | 40 ++++++++++++
 TD01/code/rod-cutting.py                | 20 ++++++
 TD01/code/set-duplicatas.py             | 11 ++++
 TD01/code/time.py                       |  7 ++
 11 files changed, 269 insertions(+), 1 deletion(-)
 create mode 100755 TD01/code/comprehension-list-filter.py
 create mode 100644 TD01/code/exceptions.py
 create mode 100644 TD01/code/format.py
 create mode 100644 TD01/code/listes.py
 create mode 100644 TD01/code/premier.py
 create mode 100644 TD01/code/recherche-dichotomie-place.py
 create mode 100644 TD01/code/recherche-dichotomie.py
 create mode 100644 TD01/code/rod-cutting.py
 create mode 100644 TD01/code/set-duplicatas.py
 create mode 100644 TD01/code/time.py

diff --git a/TD01/code/addition.py b/TD01/code/addition.py
index 7bcc0fd..4ba4f40 100644
--- a/TD01/code/addition.py
+++ b/TD01/code/addition.py
@@ -1,6 +1,6 @@
 def addition(a, b):
     return a + b
-
+    
 def addition_inf(*argv):
     res = 0
     for arg in argv:  
diff --git a/TD01/code/comprehension-list-filter.py b/TD01/code/comprehension-list-filter.py
new file mode 100755
index 0000000..95bff0a
--- /dev/null
+++ b/TD01/code/comprehension-list-filter.py
@@ -0,0 +1,8 @@
+carres = []
+for x in range(10):
+    if x % 2:
+        carres.append(x * x)
+
+list(map(lambda x: x * x,  filter(lambda x: x % 2, range(10))))
+
+[x * x for x in range(10) if x % 2]
diff --git a/TD01/code/exceptions.py b/TD01/code/exceptions.py
new file mode 100644
index 0000000..6ed74a9
--- /dev/null
+++ b/TD01/code/exceptions.py
@@ -0,0 +1,33 @@
+# https://docs.python.org/3/tutorial/errors.html
+import addition
+
+class Error(Exception):
+    """Classe de base d'exceptions"""
+    pass
+
+class ValueTooSmallError(Error):
+    """Si la valeur est trop petite"""
+    pass
+
+if __name__ == "__main__":
+
+    a, b = 1, 2
+
+    try:
+        if a < 0 or b < 0:
+            raise ValueTooSmallError
+        # assert addition(a, b) == 3
+        # assert not addition(a, b) == 4
+        # addition(a, "c")
+
+        # raise EnvironmentError
+    except AssertionError:
+        print("test non validé")
+    except TypeError:
+        print("problème de typage")
+    except ValueTooSmallError:
+        print("valeur trop petite")
+    except:
+        print("erreur inconnue")
+    finally:
+        print("c'est la fin, toujours exécuté")
diff --git a/TD01/code/format.py b/TD01/code/format.py
new file mode 100644
index 0000000..9f2cb3a
--- /dev/null
+++ b/TD01/code/format.py
@@ -0,0 +1,87 @@
+from math import pi
+
+s = "Python"
+s.center(10)         # centrer sur 10 positions
+print(s)
+# Donne -->'  Python  '
+
+s.center(10,"*")       # centrer sur 10 positions en complétant par des '*'
+# Donne -->'**Python**'
+print(s)
+
+s = "Training"
+s.ljust(12)           # justifier à gauche sur 12 positions} 
+# Donne -->'Training    '
+print(s)
+
+s.ljust(12,":")
+# Donne -->'Training::::'
+
+s = "Programming"
+s.rjust(15)
+# Donne -->'    Programming'
+s.rjust(15, "~")
+# Donne -->'~~~~Programming'
+
+account_number = "43447879"
+account_number.zfill(12)
+# Donne -->'000043447879'
+
+# Même chose avec rjust : 
+account_number.rjust(12,"0")
+# Donne -->'000043447879'
+
+s = 'Hello, world.'
+str(s)
+# Donne -->'Hello, world.'
+
+repr(s)
+# Donne --> "'Hello, world.'"
+str(1/7)
+# Donne --> '0.14285714285714285'
+
+r=2
+print("La surface pour un rayon {rayon:3d} sera {surface:8.3f}".format(surface=r*r*pi, rayon=r))
+# Donne -->  'La surface pour un rayon   2 sera   12.566'
+
+x = 10 * 3.25
+y = 200 * 200
+s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
+print(s)
+# Donne --> The value of x is 32.5, and y is 40000...
+
+# Le repr() d'un string ajoute des quotes et backslashes:
+hello = 'hello, world\n'
+str(hello)
+# Donne --> 'hello world\n'
+repr(hello)
+# Donne --> 'hello, world\\n' %*  {\color{magenta}  noter le double slash}    *)
+
+# L'argument d'appel de repr() peut être n'importe quel objet  Python :
+repr((x, y, ('spam', 'eggs')))
+# Donne -->"(32.5, 40000, ('spam', 'eggs'))"
+
+for x in range(1, 11):
+    print(repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4))
+# Donne -->
+#  1   1    1
+#  2   4    8 
+#  3   9   27
+#  4  16   64
+#  5  25  125
+#  6  36  216
+#  7  49  343
+#  8  64  512
+#  9  81  729
+# 10 100 1000
+
+for x in range(1, 6):
+    print(repr(x).rjust(2), end='#'*x+'\n')    # on ajoute x fois \# + \textbackslash n à la fin de chaque ligne}  *)
+
+# Donne -->
+#  1#
+#  2##
+#  3###
+#  4####
+#  5##### 
+# 
\ No newline at end of file
diff --git a/TD01/code/listes.py b/TD01/code/listes.py
new file mode 100644
index 0000000..8c4eab0
--- /dev/null
+++ b/TD01/code/listes.py
@@ -0,0 +1,5 @@
+
+
+L = []
+
+L.ap    
\ No newline at end of file
diff --git a/TD01/code/premier.py b/TD01/code/premier.py
new file mode 100644
index 0000000..8b21ec0
--- /dev/null
+++ b/TD01/code/premier.py
@@ -0,0 +1,30 @@
+from math import sqrt
+
+def premier(a):
+
+    # si == 1 ou ==2
+    if(a == 1 or a== 2):
+        return True
+    # si pair
+    elif(a % 2 == 0):
+        return False
+    else:
+        if (int(sqrt(a)) == sqrt(a)):
+            return False
+        
+        for k in range(3, int(sqrt(a)+1), 2):
+            if a % k == 0:
+               return False
+        
+        return True 
+    # autre
+
+assert premier(1) == True
+assert premier(2) == True
+assert premier(4) == False
+assert premier(9) == False
+
+assert premier(3) == True
+assert premier(20) == False
+assert premier(23) == True
+assert premier(6067) == True
diff --git a/TD01/code/recherche-dichotomie-place.py b/TD01/code/recherche-dichotomie-place.py
new file mode 100644
index 0000000..c5995a7
--- /dev/null
+++ b/TD01/code/recherche-dichotomie-place.py
@@ -0,0 +1,27 @@
+def trouveOuDitOuInserer(sequence, val, inf=0, sup=None):
+    if sup is None:
+        sup = len(sequence)-1
+    if sup < inf :
+        return inf
+    mid = (inf + sup) // 2  
+    if sequence[mid] == val:  return mid
+    if sequence[mid] < val:   inf = mid + 1
+    else: sup = mid-1
+    return trouveOuDitOuInserer(sequence, val, inf, sup)
+3
+ary = (2, 3, 4,  6, 7,9,10, 12, 13)
+print('On cherche dans ', ary, ' et les places sont : ')
+print('7 ', trouveOuDitOuInserer(ary, 7, 0, len(ary) -1));input('?'); 
+print('2 ',trouveOuDitOuInserer(ary, 2, 0, len(ary) -1));input('?')
+print('5 ',trouveOuDitOuInserer(ary, 5, 0, len(ary) -1));input('?')
+print('15', trouveOuDitOuInserer(ary, 15, 0, len(ary) -1));input('?')
+print('1', trouveOuDitOuInserer(ary, 1, 0, len(ary) -1));input('?')
+
+""" tests
+On cherche dans  (2, 3, 4, 6, 7, 9, 10, 12, 13) et les places sont : 
+7  4
+2  0
+5  3
+15 9
+1  0
+"""
\ No newline at end of file
diff --git a/TD01/code/recherche-dichotomie.py b/TD01/code/recherche-dichotomie.py
new file mode 100644
index 0000000..f1400ca
--- /dev/null
+++ b/TD01/code/recherche-dichotomie.py
@@ -0,0 +1,40 @@
+from random import randint;
+
+def dichotomie(liste, val):
+    print("La liste reçue : ",liste, ' de taille ', len(liste))
+    if liste==[] : return False
+    m=len(liste)//2
+    print('\ton compare liste[',m,']=', liste[m], ' et ', val) 
+    if liste[m] == val: return True
+    elif liste[m] > val: return dichotomie(liste[:m], val)     # dans liste[:m], liste[m] n'est pas inclu.
+    else: return dichotomie(liste[m+1:], val)                  # dans liste[X:],  liste[X]  est  inclu.
+ 
+ll=[randint(1,50) for i in range(10)]  
+ll.sort()
+x=int(input("chercher une valeur entre 1 et 50 dans la liste " + repr(ll) + " ? : "))
+print("La présence de  ", x, " dans la liste : ", ll, dichotomie(ll, x))    
+
+"""  
+# Et un cas de succès : 
+chercher une valeur entre 1 et 50 dans la liste [4, 7, 10, 14, 19, 27, 31, 32, 35, 47] ? : 32
+La liste reçue :  [4, 7, 10, 14, 19, 27, 31, 32, 35, 47]  de taille  10
+on compare liste[ 5 ]= 27  et  32
+La liste reçue :  [31, 32, 35, 47]  de taille  4
+on compare liste[ 2 ]= 35  et  32
+La liste reçue :  [31, 32]  de taille  2
+on compare liste[ 1 ]= 32  et  32
+La présence de   32  dans la liste :  [4, 7, 10, 14, 19, 27, 31, 32, 35, 47] True
+
+# Et un cas d'échec :
+chercher une valeur entre 1 et 50 dans la liste [22, 23, 30, 33, 37, 42, 42, 43, 47, 49] ? : 35
+La liste reçue :  [22, 23, 30, 33, 37, 42, 42, 43, 47, 49]  de taille  10
+on compare liste[ 5 ]= 42  et  35
+La liste reçue :  [22, 23, 30, 33, 37]  de taille  5
+on compare liste[ 2 ]= 30  et  35
+La liste reçue :  [33, 37]  de taille  2
+on compare liste[ 1 ]= 37  et  35
+La liste reçue :  [33]  de taille  1
+on compare liste[ 0 ]= 33  et  35
+La liste reçue :  []  de taille  0
+La présence de   35  dans la liste :  [22, 23, 30, 33, 37, 42, 42, 43, 47, 49] False
+"""
\ No newline at end of file
diff --git a/TD01/code/rod-cutting.py b/TD01/code/rod-cutting.py
new file mode 100644
index 0000000..cd9b448
--- /dev/null
+++ b/TD01/code/rod-cutting.py
@@ -0,0 +1,20 @@
+INT_MIN = 0
+
+def cutRod(price, n): 
+
+    # Initialisation tables de cache
+    val = [0 for x in range(n+1)] 
+    val[0] = 0
+  
+    for i in range(1, n+1): 
+        max_val = INT_MIN 
+        for j in range(i): 
+             max_val = max(max_val, price[j] + val[i-j-1]) 
+        val[i] = max_val 
+  
+    return val[n] 
+  
+if __name__=="__main__": 
+    arr = [1, 5, 8, 9, 10, 17, 17, 20] 
+    size = len(arr) 
+    print("Valeur maximum de découpe " + str(cutRod(arr, size))) 
\ No newline at end of file
diff --git a/TD01/code/set-duplicatas.py b/TD01/code/set-duplicatas.py
new file mode 100644
index 0000000..c3273ab
--- /dev/null
+++ b/TD01/code/set-duplicatas.py
@@ -0,0 +1,11 @@
+def duplicatas(L):
+	s = set()
+	for x in L:
+		if x in s:
+			return True
+		s.add(x)
+	return False
+
+if __name__=="__main__": 
+	assert duplicatas([3, 5, 3]) == True
+	assert duplicatas([3, 5, 5]) == False
diff --git a/TD01/code/time.py b/TD01/code/time.py
new file mode 100644
index 0000000..683b0f9
--- /dev/null
+++ b/TD01/code/time.py
@@ -0,0 +1,7 @@
+import timeit
+
+print(timeit.timeit("x = 2 + 2"))
+#.0188..............
+
+print(timeit.timeit("x = range(10)"))
+#.589.........
-- 
GitLab