Skip to content

Instantly share code, notes, and snippets.

@vanne02135
Created February 6, 2010 14:34
Show Gist options
  • Save vanne02135/296744 to your computer and use it in GitHub Desktop.
Save vanne02135/296744 to your computer and use it in GitHub Desktop.
Simple vector class, only element-wise multiplication and addition implemented
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