You can override the built in methods for numerical types.
class matrix: def __init__(self, string_matrix): self.matrix = string_matrix.split(";") for i in range(len(self.matrix)): self.matrix[i] = map(int, self.matrix[i].split()) def __add__(self, other): return_matrix = [[i for i in row] for row in self.matrix] for i in range(len(self.matrix)): for j in range(len(self.matrix[i])): return_matrix[i][j] = self.matrix[i][j] + other.matrix[i][j] return list_to_matrix(return_matrix) def __str__(self): return repr(self.matrix) def list_to_matrix(list_matrix): string_form = "" for row in list_matrix: for item in row: if (item != row[-1]): string_form += str(item) + " " else: string_form += str(item) if (row != list_matrix[-1]): string_form += ";" return matrix(string_form)
You will probably want to include a couple of checks (such as adding matrices of different dimensions, or adding a matrix to something that is not a matrix, etc) but this works as a simple example. Also notice that I'm returning a matrix object using the list_to_matrix() function - if that isn't the desired functionality you can change it pretty readily. You would use a similar process for all other arithmetic functions you need to implement.
Output:
>>> a = matrix("3 4;1 4") >>> b = matrix("2 3;0 0") >>> print(a) [[3, 4], [1, 4]] >>> print(b) [[2, 3], [0, 0]] >>> print(a + b) [[5, 7], [1, 4]]
As mentioned in one of the other answers, numpy might be a good resource to use for your matrix operations - a lot of this functionality is already built in.
>>> import numpy as np >>> a = np.matrix("3 4;1 4") >>> b = np.matrix("2 3;0 0") >>> print(a) [[3 4] [1 4]] >>> print(b) [[2 3] [0 0]] >>> print(a + b) [[5 7] [1 4]]