CoCalc Public Fileswww / talks / pyrex / misc / mult1.pyOpen with one click!
Author: William A. Stein
1
class Matrix:
2
def __init__(self, p, n, entries=None):
3
"""
4
Create a matrix over a finite field.
5
INPUT:
6
p -- prime
7
n -- positive integer
8
entries -- entries of the matrix (defaults to None, which means 0 matrix).
9
"""
10
self.__n = n
11
self.__p = p
12
if entries != None:
13
self.__entries = [x % p for x in entries]
14
else:
15
self.__entries = [0 for _ in range(n*n)]
16
17
def __repr__(self):
18
s = ""
19
n = self.__n
20
for i in range(n):
21
for j in range(n):
22
s += "%s, "%self.__entries[n*i + j]
23
s += "\n"
24
return s
25
26
def __mul__(self, other):
27
assert isinstance(other, Matrix) and \
28
self.__p == other.__p and \
29
self.__n == other.__n, "Incompatible multiply."
30
ans = []
31
n = self.__n
32
for i in range(n):
33
for j in range(n):
34
# The i,j entry of the product
35
v = [self.__entries[i*n+k] * other.__entries[k*n+j] for k in range(n)]
36
ans.append(sum(v) % self.__p)
37
return Matrix(self.__p, n, ans)
38
39