#!/usr/bin/env python def multiplyMatrices(A, B, fieldSize = 0): if len(A[0]) != len(B): raise Exception, 'The number of columns of A must equal the number of rows of B' # Prepare an empty matrix with |rows(A)| rows and |columns(B)| columns. C = [ [0] * len(B[0]) for i in range(len(A)) ] for ci in range(len(C)): for cj in range(len(C[ci])): C[ci][cj] = sum([ (A[ci][i] * B[i][cj]) for i in range(len(A[0])) ]) if fieldSize > 0: C[ci][cj] %= fieldSize return C def printMatrix(matrix): print '\n'.join([ ' '.join(map(lambda x: str(x).center(3), row)) for row in matrix ]) def fancyPrint(matrix): for (i, row) in enumerate(matrix): if len(matrix) == 1: # for single-row matrices delim = '()' elif not i: # first row delim = '/\\' elif i == len(matrix) - 1: # last row delim = '\\/' else: # rows in the middle delim = '||' print delim[0], ' '.join(map(lambda x: str(x).center(3), row)), delim[1] A = ( (10, 2, 9), (4, 8, 7), (3, 8, 0) ) B = ( (2, 10, 6), (2, 10, 2), (6, 5, 10) ) M = multiplyMatrices(A, B, 11) fancyPrint(M) N = multiplyMatrices(A, B) fancyPrint(N) C = ( (4, 2, 1), (-1, 0, 1) ) D = ( (3, 1), (1, 1), (2, 5) ) O = multiplyMatrices(C, D, 7) P = multiplyMatrices(D, C, 7) fancyPrint(O) print fancyPrint(P)