Created
February 6, 2010 14:34
-
-
Save vanne02135/296744 to your computer and use it in GitHub Desktop.
Simple vector class, only element-wise multiplication and addition implemented
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
import array | |
class vector(): | |
def __init__(self, d): | |
if type(d) is int: | |
self.data = array.array('f', [0]*d) | |
elif type(d) is list: | |
self.data = array.array('f', d) | |
else: | |
raise TypeError("Only int or list, please") | |
def __repr__(self): | |
return self.data.tolist().__repr__() | |
def __getitem__(self, i): | |
return self.data(i) | |
def __eq__(self, other): | |
return not False in [self.data[i] == other.data[i] for i in xrange(len(self.data))] | |
def size(self): | |
return len(self.data) | |
def plus(self, other): | |
if self.size() != other.size(): | |
raise Exception("Size mismatch") | |
return vector([self.data[i] + other.data[i] for i in xrange(self.size())]) | |
def times(self, other): | |
if type(other) is float or type(other) is int: | |
return vector([self.data[i] * other for i in xrange(self.size())]) | |
if self.size() != other.size(): | |
raise Exception("Size mismatch") | |
return vector([self.data[i] * other.data[i] for i in xrange(self.size())]) | |
if __name__ == "__main__": | |
A = vector(range(10)) | |
B = vector(range(10)) | |
C = A.plus(B) | |
D = C.times(B) | |
print A | |
print C | |
print D | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment