Skip to content

Instantly share code, notes, and snippets.

@alarsyo
Last active September 22, 2016 19:45
Show Gist options
  • Save alarsyo/75422269f3edaef1a3238d3f64b903fe to your computer and use it in GitHub Desktop.
Save alarsyo/75422269f3edaef1a3238d3f64b903fe to your computer and use it in GitHub Desktop.
### Correction des fonctions du lundi 19/09 ###
def print_mat(M, d):
s = "| {:" + str(d) + "d}"
l = len(M[0])
t = '-' * (d+3) * l + '-'
for i in range(len(M)):
print(t)
for j in range(l):
print(s.format(M[i][j]), end=' ')
print('|')
print(t)
def init_mat(l, c, val):
m = []
for i in range(l):
n = []
for j in range(c):
n.append(val)
m.append(n)
return m
### Correction de ce qui a été fait le jeudi 22/09 ###
def add_mat(A, B):
(lA,cA) = (len(A), len(A[0]))
if lA != len(B) or cA != len(B[0]):
raise Exception("Wrong sizes")
C = init_mat(lA, cA, 0)
for i in range(lA):
for j in range(cA):
C[i][j] = A[i][j] + B[i][j]
return C
def mult_mat(A, B):
(lA, cA, lB, cB) = (len(A), len(A[0]), len(B), len(B[0]))
if cA != lB:
raise Exception("Wrong sizes")
C = init_mat(lA, cB, 0)
for i in range(lA):
for j in range(cB):
for k in range(cA): # ou range(lB)
C[i][j] = C[i][j] + A[i][k] * B[k][j]
return C
def isMagic(m): # correction
n = len(m[0])
if len(m) != n:
return False
magic = True
(i, res, d1, d2) = (0, 0, 0, 0)
while i < n and magic :
(sl, sc) = (0, 0)
d1 += m[i][i]
d2 += m[i][n - i - 1]
for j in range(n):
sl += m[i][j]
sc += m[j][i]
magic = (sl == sc) and (sl == res or i == 0)
res = sl
i += 1
return (magic and d1 == d2 and d1 == res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment