""" Demonstrates how to implement and work with matrices """ import random def zero_matrix(size): """ Returns a size x size matrix of zeros :param size: (int) the size of the matrix :return: (list) the matrix of zeros """ m = [] for i in range(size): row_list = [] for j in range(size): row_list.append(0) m.append(row_list) return m def zero_matrix2(size): """ An alternative implementation Returns a size x size matrix of zeros :param size: (int) the size of the matrix :return: (list) the matrix of zeros """ m = [] for i in range(size): m.append([0] * size) return m def random_matrix(size): """ Returns a size x size matrix of random numbers between 0 and size*size :param size: (int) the size of the matrix :return: (list) the matrix of random numbers in [0, size*size] """ m = [] for i in range(size): row_list = [] for j in range(size): row_list.append(random.randint(0, size * size)) m.append(row_list) return m def print_matrix(m): """ Prints the contents of the matrix m :param m: (list) the matrix to print :return: (None) """ for row in m: print(row) def print_matrix2(m): """ An alternative implementation Prints the contents of the matrix m :param m: (list) the matrix to print :return: (None) """ for row_number in range(len(m)): print(m[row_number]) def identity(size): """ Returns an identity size x size matrix (zeros everywhere and ones on the diagonal) :param size: (int) the size of the matrix :return: (list) the identity matrix """ m = zero_matrix(size) for i in range(size): m[i][i] = 1 return m def matrix_sum(m): """ Returns the sum of the contents of the matrix m :param m: (list) the matrix to sum its contents :return: (int) the sum of the contents of matrix m """ total = 0 for r in range(len(m)): for c in range(len(m[r])): total += m[r][c] return total def matrix_sum2(m): """ Alternative implementation Returns the sum of the contents of the matrix m :param m: (list) the matrix to sum its contents :return: (int) the sum of the contents of matrix m """ total = 0 for row in m: for value in row: total += value return total def matrix_sum3(m): """ Alternative implementation Returns the sum of the contents of the matrix m :param m: (list) the matrix to sum its contents :return: (int) the sum of the contents of matrix m """ total = 0 for row_number in range(len(m)): total += sum(m[row_number]) return total def matrix_sum4(m): """ Alternative implementation Returns the sum of the contents of the matrix m :param m: (list) the matrix to sum its contents :return: (int) the sum of the contents of matrix m """ total = 0 for row in m: total += sum(row) return total