Informatique Terminale : Compléments de programmation
Code complet du sujet 1 :
class Iterateur:
def __init__(self, carre):
self.courant = 0 self.carre = carre
def __next__(self):
n = self.carre.taille() if self.courant>=n**2:
raise StopIteration
ret = self.carre(self.courant//n, self.courant%n) self.courant += 1
return ret
class Carre:
def __init__(self, lignes):
self.lignes = lignes
def __call__(self, i, j):
return self.lignes[i][j]
def taille(self):
return len(self.lignes)
def largeur(self):
mini = 0
for lig in self.lignes:
for x in lig:
if x > mini:
mini = x return len(str(mini))
def __str__(self):
larg = self.largeur() ligne = ''
for lig in self.lignes:
ligne += '['
for i in range(len(lig)-1):
ligne += ' '*(larg-len(str(lig[i]))) + str(lig[i]) + ', ' ligne += ' '*(larg-len(str(lig[-1]))) + str(lig[-1]) + ']\n' return ligne
def uniques(self):
d = {}
for l in self.lignes:
for x in l:
d[x] = 1
return len(d)==self.taille()**2
def Nul(n):
lignes = []
for i in range(n):
lignes.append([0]*n) return Carre(lignes)
#def Nul(n): return Carre([[0]*n]*n)
def Id(n):
c = Carre.Nul(n) for i in range(n):
c.lignes[i][i] = 1 return c
def __add__(self, carre):
n = self.taille() lignes = []
for i in range(n):
ligne = []
for j in range(n):
ligne.append(self.lignes[i][j] + carre.lignes[i][j]) lignes.append(ligne)
return Carre(lignes)
def __contains__(self, valeur):
n = self.taille() for i in range(n):
for j in range(n):
if valeur==self.lignes[i][j] : return True return False
def __iter__(self):
return Iterateur(self)
A = Carre([[2, 3, 4], [5, 1, 7], [6, 9, 8]]) B = Carre([[7, 6, 5], [4, 8, 2], [3, 0, 1]]) print(A.lignes)
print(B.lignes)
print("#########################") print(A)
print(B) print(A+B)
print("#########################") print(A.lignes[1][0])
print(A(1, 0))
print("#########################")
# Tester le code ci-dessous avec les deux écritures de la méthode Nul A = Carre.Nul(3)
B = Carre.Id(3) print(B)
print(id(B.lignes[0]), id(B.lignes[1])) print("#########################")
A = Carre([[2, 3, 4], [5, 1, 7], [6, 9, 8]]) print(list(A))
for x in A: print(x)
print("Somme : " + str(sum(A))) print("Maximum : " + str(max(A))) print("Minimum : " + str(min(A)))