Informatique/SPE/IPT/TD1 Exos programmation/exo3.py

56 lines
1.8 KiB
Python
Raw Normal View History

2020-09-15 18:55:13 +02:00
#!/usr/bin/env python3
class Question:
def __init__(self,i=1, l=0, n=''):
self.name=n
self.level=l
self.number=i
def __enter__(self):
print('\n' + (self.level*2)*' ' + f"-> {self.number}. : {self.name} -- Début")
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
print((self.level*2)*' ' + f"<- {self.number}. : {self.name} -- Fin\n")
import numpy as np
import random
with Question(3):
A = np.reshape(np.array([random.randint(0,9) for _ in range(9*9)]), (9,9))
B = np.reshape(np.array([random.randint(0,9) for _ in range(2*2)]), (2,2))
print(A)
print(B)
def motif(B, A):
for i in range(A.shape[0] - B.shape[0] + 1):
for j in range(A.shape[1] - B.shape[1] + 1):
diff = False
for k in range(B.shape[0]):
for l in range(B.shape[1]):
if B[k][l]!=A[i+k][j+l]:
diff = True
break
if diff:
break
if not diff:
return True
return False
print(motif(B, A))
def S(A, B):
s = 0
for i in range(A.shape[0]):
for j in range(A.shape[1]):
s += (A[i][j] - B[i][j])**2
return s
def proche_motif(B, A):
M = np.zeros((A.shape[0] - B.shape[0] + 1, A.shape[1] - B.shape[1] + 1))
mini = (0,0)
for i in range(A.shape[0] - B.shape[0] + 1):
for j in range(A.shape[1] - B.shape[1] + 1):
M[i][j] = S(B, A[i: i +B.shape[0], j: j + B.shape[1]])
if M[mini[0]][mini[1]] > M[i][j]:
mini = (i,j)
return A[mini[0]: mini[0] +B.shape[0], mini[1]: mini[1] + B.shape[1]]
print(proche_motif(B,A))