VaultBy ENSAMIENParrainage
Notebook

Site intéressant : https://www.w3schools.com/python/

05-tableaux-matrices-fichiers.ipynb

MyDict = {
  "brand": "Hyundai",
  "model": "Accent",
  "year": 2024,
  "model": "Elantra"
}
print(MyDict)
  • Conclusion : La dernière utilisation écrase la valeur de la première utilisation

Tableaux :

- Python ne prend pas en charge les tableaux, mais les listes Python peuvent être utilisées à la place.

  • Ci-dessous :
    • comment utiliser les LISTES comme TABLEAUX,
    • cependant, pour travailler avec des tableaux en Python, il faut importer une bibliothèque, comme array ou numpy.

- from array import array

from array import array

t = array("i", [10, 20, 30, 40])
# t = array("f", [10, 20, 30, 40])
# t = array("i", [1, 2, 3, 4, "7", 6])
# t = array("i", [10, 20, 30, 40.0])
# t = array([10, 20, 30, 40.0])

print(t, type(t))
print("Len :", len(t))

print("Prem :", t[0], ", Dern :", t[-1])

print("parcours:")
for i in t:
    print(i, end = " ")

# print(t)

- import numpy as np

import numpy as np
tab = np.array([10, 12, 8])
print(tab ,  type(tab))
  • Expliciter le type
TC = np.array([10, 12, 8], dtype=complex)

print(TC, type(TC))
  • Conversion Implicite (Upcasting)
# timp = np.array([1, 2.0, 3])
# timp = np.array([10, 12, 8, 11, "100"])
# timp = np.array([10, 12, 8, 11 , 3.5, "100"])

print(timp)
  • Parcourir un tableau :
tab = np.array([10, 12, 8])

for elem in tab:
    print(elem, end = " ")
  • Dimensions minimales 2 :
Tmin = np.array([21, 32, 13], ndmin=2) # Matrice
print("Tmin    :" , Tmin, type(Tmin))

print("Tmin[0] :", Tmin[0])
Tmin = np.array([21, 32, 13]) # Matrice
print("Tmin    :" , Tmin, type(Tmin))

print("Tmin[0] :", Tmin[0])
Tmin = np.array([210, 320, 130], ndmin=3) # tableau de Matrices
print(Tmin, type(Tmin))

print(Tmin[0][0]) # afficher pour ndmin = 2, 3

Produit Scalaire

import numpy as np
a = np.array([1, 3, 4])
b = np.array([20, 10, 30])

print(type(a))
# PS : Manuellement
m = len(a)
ps = 0
for i in range(m):
    ps += a[i] * b[i]

print("Produit Scalaire Manuel :",ps)
# PS : Méthode 1 : .dot()
print("Produit Scalaire np.dot() :",np.dot(a ,b))
# PS : Méthode 2
print("Produit Scalaire np.dot(a, b)              :",np.dot(a ,b))
print("Produit Scalaire np.dot(a.T , b)           :",np.dot(a.T ,b))
print("Produit Scalaire np.dot(a.Transpose() , b) :",np.dot(a.transpose() ,b))
# PS : Méthode 3
print("Produit Scalaire   a @ b   :", a@b)
print("Produit Scalaire a.T @ b   :", a.T@b)
# PS : Méthode 4
print("Produit Scalaire np.inner( a, b) :", np.inner(a,b))
print("Produit Scalaire np.inner(a.T,b) :", np.inner(a.T,b))

Produit terme à terme

a = np.array([4, 5, 6])
b = np.array([2, 1, 3])
prod = a * b
print(prod)

Matrices : Tableaux de plus d'une dimension

import numpy as np

tm = np.array([[10, 20, 70], [30, 40, 90]])

print(tm)
print("size  :", np.size(tm) , "     # Nombre d'elements")
print("shape :", np.shape(tm))
print("len   :", len(tm) ,     "     # Nombre de lignes")
x = tm[0][1]
print(x)
y = tm[0,0]
print(y)
print("tm[0]: ", end = "")
print(tm[0])
import numpy as np

Lm = ([[10, 200], [30, 40], [50, 60]])
print("\nPour la liste aussi :\n")
print(Lm)
print("size  :", np.size(Lm), "     # Nombre d'elements")
print("shape :", np.shape(Lm))
print("len   :", len(Lm),  "     # Nombre de lignes")

Afficher une Matrice:

import numpy as np
Mat = np.array([[10, 20, 70], [30, 40, 90], [100, 200, 300]])
print(Mat)
# Méthode 1:
import numpy as np

Mat = np.array([[10, 20, 70], [30, 40, 90], [100, 200, 300]])
m,n = np.shape(Mat)

for i in range(m):
    for j in range(n):
        print(f"{Mat[i][j]:3d}" , end = " ")
    print("")
# Méthode 2:
import numpy as np
Mat = np.array([[10, 20, 70], [30, 40, 90], [100, 200, 300]])
for Lg in Mat:
    for el in Lg:
        print(f"{el:3d}", end = " ")
    print("")
# Méthode Ligne:
import numpy as np
Mat = np.array([[10, 20, 70], [30, 40, 90], [100, 200, 300]])
for Lg in Mat:
    print(Lg)

Modifier les éléments d'une matrice

# Méthode 1:
import numpy as np

Mat = np.array([[10, 20, 70], [30, 40, 90], [100, 200, 300]])
m,n = np.shape(Mat)

for i in range(m):
    for j in range(n):
        Mat[i][j] += 1 
        print(f"{Mat[i][j]:3d}" , end = " ")
    print("")
# Méthode 2:
import numpy as np

Mat = np.array([[10, 20, 70], [30, 40, 90], [100, 200, 300]])

for Lg in Mat:
    for el in Lg:
        el = el+1
        print(f"{el:3d}", end = " ")
    print("")
import numpy as np

Mat = np.array([[10, 20, 70], [30, 40, 90], [100, 200, 300]])
B = Mat + 1

print(B)

Comparer Deux matrices

X = np.array([[10, 20, 70], [30, 40, 90], [100, 200, 300]])
Y = np.array([[10, 20, 70], [30, 40, 90], [100, 200, 300]])

R = (X == Y)

print(R)
print(R.all())

Produits matriciels de A et B:

- A@B 
- np.dot(A,B)
- A*B : Element By Element
import numpy as np

A = np.array([[10, 20, 70], [30, 40, 90], [100, 200, 300]])
B = np.array([[1, 2, 3], [6, 5, 4], [7, 9, 8]])
# B = np.array([[10, 20], [30, 40], [100, 200]])

print(f"\nA {np.shape(A)}: \n", A)
print(f"\nB {np.shape(B)}: \n", B)

AT = A@B
print(f"\nA@B : {np.shape(AT)}: \n", AT)

DOT = np.dot(A,B)
print(f"\ndot : {np.shape(DOT)}: \n", DOT)
Res = (DOT == AT)
print("Produit .dot() == @ :", Res.all())

Produit Matriciel élément / élément

A = np.array([[10, 20, 70], [30, 40, 90], [100, 200, 300]])
B = np.array([[1, 2, 3],    [6, 5, 4],    [7, 9, 8]])

PL = A*B
print(f"\nElem By Elem : {np.shape(PL)}: \n", PL)

Transposée d'une Matrice

import numpy as np

Mat = np.array([[10, 20, 70], [30, 40, 90]])

TrMat = Mat.transpose()
print(f"Matrice Transpose  : {np.shape(TrMat)}\n",TrMat)

TrsMat2 = Mat.T
print(f"Matrice 2 Transpose : {np.shape(TrMat)}\n",TrsMat2)
ResTr = (TrMat == TrsMat2)
print("transposee .transpose() == .T :", ResTr.all())

Matrice Complexe conjugué - numpy.conj()

u = np.array([[  2j, 4+3j],
              [2+5j, 5],
              [3, 6+2j]])

print("u :\n",u)

print("")
uConj = np.conj(u)
print("Conj u :\n",uConj)

Matrice Transposée conjuguée (adjointe):

u = np.array([[  2j, 4+3j],
                  [2+5j, 5   ],
                  [   3, 6+2j]])
print("u :\n",u)
print("Adjointe u :\n",np.conj(u.T))

Application : Matrice Unitaire

- Une matrice U est unitaire si sa Matrice adjointe U*
  (Transposée conjuguée de U) vérifie :

  U* x U = U x U* = Id 
def matUnit(A):
    # Voire TDP
MA = np.array([[0, 1],[1, 0]])
print("MA :\n", MA)
import numpy as np
MB = np.array([[ 0, -3.j],
                [1.j, 0  ]])

print("MB :\n", MB)
# print("Unitaire : ", matUnit(MB))
import numpy as np
MC = np.array([[ 0, -1.j],
                  [1.j, 0  ]])

print("MC :\n", MC)
# print("Unitaire : ", matUnit(MC))

Déterminant - numpy.linalg.det()

from numpy.linalg import det
mt = np.array([[2, 2],
                 [3, 4]])

print(det(mt))
print(round(det(mt)))
# ------------ !!! ATTENTION : ne pas utiliser int() !!!
print(int(det(mt))) 
def deter(a):
    return a[0][0]*a[1][1] - a[1][0]*a[0][1] 

print(deter(mt))

Inverse - numpy.linalg.inv()

from numpy.linalg import inv
a = np.array([[1, 3, 3],
                  [1, 4, 3],
                  [1, 3, 4]])

print(inv(a))

print("\nVerif a * inv(a) :")
c = a@inv(a)

print(c)

Redimensionner une matrice

a = np.arange(12).reshape((3, 4))
print(a)
import numpy as np

Mat = np.array([[10, 20, 70], [30, 40, 90]])
print(np.shape(Mat))

print("")
NouvMat = Mat.reshape(3,2)
print(np.shape(NouvMat))

print("\n")
print(f"Matrice : {np.shape(Mat)}\n",Mat)

print("\n")
print(f"Matrice R: {np.shape(NouvMat)}\n",NouvMat)
a = np.arange(12).reshape((3, 4))
print("A :\n", a)

print("")
b = a.reshape(4,3)
print("B :\n", b)

print("")
c = b.reshape(6,2)
print("C :\n", c)

Fichiers :

  • Python dispose de plusieurs fonctions pour créer, lire et mettre à jour des fichiers.
  • La fonction clé pour travailler avec des fichiers en Python est la fonction open().

  • La fonction open() prend deux paramètres : le nom du fichier et le mode.

  • Il existe quatre méthodes différentes (modes) pour ouvrir un fichier :

    • "r" - Read - Valeur par défaut. Ouvre un fichier en lecture, erreur si le fichier n'existe pas.

    • "a" - Append - Ouvre un fichier pour l'ajouter, crée le fichier s'il n'existe pas.

    • "w" - Write - Ouvre un fichier pour l'écriture, crée le fichier s'il n'existe pas.

    • "x" - Create - Crée le fichier spécifié, renvoie une erreur si le fichier existe.

  • En outre, vous pouvez spécifier si le fichier doit être traité en mode binaire ou en mode texte

    • "t" - Texte - Valeur par défaut. Mode texte

    • "b" - Binaire - Mode binaire (par exemple, images)

ATTENTION : à chaque open() il faut associer automatiquement un close()

Ouverture en lecture "r"

Lire tout le fichier d'un seul coup

f = open("etudiants.txt")
# f = open("demofile.txt", "rt")

print("Debut")
print(f.read()) # affiche tout le fichier
print("Fin")
f.close()

Lire le fichier Ligne par Ligne

f = open("etudiants.txt", "rt")

for x in f:
    print("New Line : ", end = "")
    print(x)
f.close()
f = open("etudiants.txt")

x = f.readline()
while(x):
    print(x)
    x = f.readline()
f.close()

Ouverture en ajout "a"

f = open("etudiants.txt" , "a")
f.write("\nHind:23:F:5:Oujda")
f.close()

f = open("etudiants.txt")
print(f.read()) # affiche tout le fichier
f.close()

Ouverture en écriture "w" (écrase l'existant)

f = open("etudiants.txt", "w")
f.write("Fatal Error ! I have deleted the content !")
f.close()


f = open("etudiants.txt")
print(f.read()) # affiche tout le fichier
f.close()

Ouverture en écriture "x" (Erreur si le fichier existe)

f = open("etudiants.txt", "x")
f.write("Fatal Error 22 ! I have deleted the content !")
f.close()

f = open("etudiants.txt")
print(f.read()) # affiche tout le fichier
f.close()
f = open("etudiants.txt")
print(f.read()) # affiche tout le fichier
f.close()

Fin

    Type at least 2 letters. ↑ ↓ to move, Enter to open.