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