/projects/lattice-enumeration/
"Defines a fixed-dimensional vector class"
import copy
class Vector(object):
"A fixed-dimensional vector"
def __init__(self, dimension):
"""Initializes the vector. If an integer is given, a
vector with values 0 (of type int) will be created
in that dimension. If a tuple, list or Vector is
given, a copy will be created and used as the
vector."""
if type(dimension) == int:
self.data = dimension * [0];
elif type(dimension) == Vector:
self.data = copy.deepcopy(dimension.data); # create a copy
else:
self.data = list(dimension);
def __len__(self):
"Returns the dimension of the vector"
return len(self.data)
def __getitem__(self, k):
"Returns the k-th component of the vector"
return self.data[k]
def __setitem__(self, k, x):
"Sets the k-th component of the vector"
if type(k) == slice:
# we want to avoid that the user uses this to
# change the dimension of the vector
raise RuntimeError("No slice writing support for Vectors implemented!")
self.data[k] = x
def __add__(self, v):
"Computes the sum of this vector and v"
if type(v) != Vector:
return NotImplemented
if len(self.data) != len(v.data):
raise RuntimeError("Vectors have different dimensions!")
res = Vector(self)
for i in xrange(len(res.data)):
res[i] += v[i]
return res
def __sub__(self, v):
"Computes the difference of this vector and v"
if type(v) != Vector:
return NotImplemented
if len(self.data) != len(v.data):
raise RuntimeError("Vectors have different dimensions!")
res = Vector(self)
for i in xrange(len(res.data)):
res[i] -= v[i]
return res
def __neg__(self):
"Computes the negative of the given vector"
res = Vector(self)
for i in xrange(len(res.data)):
res[i] = -res[i]
return res
def __pos__(self):
"Computes the positive of the given vector"
res = Vector(self)
for i in xrange(len(res.data)):
res[i] = +res[i]
return res
def __mul__(self, k):
"Computes the scalar product of this vector and k"
if type(k) is Vector:
res = 0
for i in xrange(len(self.data)):
res += self[i] * k[i]
else:
res = Vector(self)
for i in xrange(len(res.data)):
res[i] *= k
return res
def __rmul__(self, k):
"Computes the scalar product of this vector and k"
res = Vector(self)
for i in xrange(len(res.data)):
res[i] *= k
return res
def __eq__(self, v):
"Check self and vector v for equality"
equal = True
for i in xrange(len(self.data)):
equal &= self.data[i] == v[i]
return equal
def __str__(self):
"Converts vector to a string"
s = "["
for i in xrange(len(self.data)):
if i != 0:
s += ", "
s += str(self.data[i])
s += "]"
return s
def __repr__(self):
"Converts vector to a string"
s = "Vector(["
for i in xrange(len(self.data)):
if i != 0:
s += ", "
s += repr(self.data[i])
s += "])"
return s