0
Here comes the code:
import numpy as np
def invert(matrix):
try:
new = list(np.linalg.inv(matrix))
except np.linalg.LinAlgError:
return "Matrix not inversible!"
for i in range(len(new)):
new[i] = list(new[i])
return new
def mxmult(x, y):
ls=[]
for i in range(len(x)): #generate null matrix
ls.append([])
for j in range(len(y[0])):
ls[i].append(0)
for i in range(len(x)):
for j in range(len(y[0])):
for k in range(len(y)):
ls[i][j] += x[i][k] * y[k][j]
return ls
def encrypt(text, matrix):
text_matrix = [[ord(letter) for letter in text][i:i+len(matrix[0])] for i in range(0, len(text), len(matrix))] #error?
print(text_matrix)
return mxmult(matrix, text_matrix)
def decrypt(text_matrix, inverse_matrix):
decoded = mxmult(inverse_matrix, text_matrix)
print(decoded)
original_text = []
for row in decoded:
for column in row:
print(column)
original_text.append(chr(int(column)))
return ''.join(original_text)
When I run the following tests
print(invert([[2, 3], [4, 5]]))
print(invert([[2, 3], [4, 6]]))
print(invert([[1,2,3], [4,5,6], [7,8,9]]))
print(mxmult([[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]]))
print(mxmult([[7,8,9], [10,11,12]], [[1,2,3], [4,5,6]]))
x = encrypt('ola como ', [[1,2,3], [4,5,6], [7,8,9]])
print(x)
print(decrypt(x, invert([[1,2,3], [4,5,6], [7,8,9]])))
get that:
[[-2.5, 1.5], [2.0, -1.0]]
Matrix not inversible!
[[-4503599627370498.0, 9007199254740992.0, -4503599627370494.5], [9007199254740996.0, -1.8014398509481984e+16, 9007199254740990.0], [-4503599627370498.0, 9007199254740992.0, -4503599627370495.5]]
[[27, 30, 33], [78, 87, 96]]
[[39, 54, 69], [54, 75, 96]]
[[111, 108, 97], [32, 99, 111], [109, 111, 32]]
[[502, 639, 415], [1258, 1593, 1135], [2014, 2547, 1855]]
[[2048.0, 4096.0, 2048.0], [-2048.0, -4096.0, -2048.0], [0.0, 2048.0, 0.0]]
2048.0
4096.0
2048.0
-2048.0
Traceback (most recent call last):
File "C:\...", line 54, in <module>
print(decrypt(x, invert([[1,2,3], [4,5,6], [7,8,9]])))
File "C:\...", line 42, in decrypt
original_text.append(chr(int(column)))
ValueError: chr() arg not in range(0x110000)
Because when I invert a 2x2 matrix it works, but a 3x3 generates absurd results?
Because when I decrypt it generates strange numbers (negative, repeated)?
How do I make when executing Encrypt() the number of rows of text_matrix is equal to the number of columns of the parameter Matrix and so I can multiply them?