Created
March 18, 2016 09:29
-
-
Save pahaz/39ca727653fad38b1205 to your computer and use it in GitHub Desktop.
Matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
class Matrix: | |
def __init__(self, m): | |
self.m = m | |
def __str__(self): | |
return "Matrix(%r)" % self.m | |
def __repr__(self): | |
return "Matrix(%r)" % self.m | |
def __add__(self, other): | |
if not isinstance(other, Matrix): | |
return NotImplemented | |
# TODO: check matrix size | |
r = [] | |
for xline, yline in zip(self.m, other.m): | |
rline = [] | |
for x, y in zip(xline, yline): | |
rline.append(x + y) | |
r.append(rline) | |
return Matrix(r) | |
def __rmul__(self, other): | |
if isinstance(other, Matrix): | |
return NotImplemented | |
elif isinstance(other, (int, float, complex)): | |
return Matrix( | |
[ | |
[x * other for x in xline] | |
for xline in self.m | |
] | |
) | |
else: | |
return NotImplemented | |
def __eq__(self, other): | |
if not isinstance(other, Matrix): | |
return NotImplemented | |
for xline, yline in zip(self.m, other.m): | |
for x, y in zip(xline, yline): | |
if x != y: | |
return False | |
return True | |
def __contains__(self, other): | |
return any([other in xline for xline in self.m]) | |
def __getitem__(self, key): | |
return self.m[key] | |
def __iter__(self): | |
return iter(self.m) | |
def __bool__(self): | |
return any(any(xline) for xline in self) | |
def __len__(self): | |
return len(self.m) | |
a = Matrix([[1, 0], [0, 1]]) | |
b = Matrix([[1, 0], [0, 1]]) | |
print(a, b) | |
print(1 in a) | |
print(len(a)) | |
print(iter(a)) | |
for x in a[0]: | |
print (x, end=' ') | |
print() | |
for xline in a: | |
print(xline) | |
if Matrix([[0, 0], [0, 0]]): | |
print('error') | |
if not Matrix([[0, 0], [0, 1]]): | |
print('error') | |
print(a + b) | |
print(a + b == Matrix([[2, 0], [0, 2]])) | |
print(2 * a) | |
print(1 * a == a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment