def __add__(self, other):
# Order of testing is important!
if isinstance(other, numpy.ndarray):
# If adding sparse and dense, result is dense
# rv = SparseVector(max(self.n, other.shape[0]), {})
rv = numpy.zeros(max(self.n, other.shape[0]), 'd')
for k in range(other.shape[0]):
rv[k] = other[k]
for k in self.values.keys():
rv[k] += self[k]
return rv
elif isSparseVector(other):
rv = SparseVector(max(self.n, other.n), {})
for k in self.values.keys():
rv[k] += self[k]
for k in other.values.keys():
rv[k] += other[k]
return rv
elif operator.isNumberType(other):
rv = SparseVector(self.n, {})
for k in self.values.keys():
rv[k] = self[k] + other
return rv
else:
raise TypeError("Cannot add with SparseVector")
评论列表
文章目录