clovis
clovis

Reputation: 335

Vector Class Adding

I've defined a class for n-dimensional vectors with:

class Vector:
    def __init__(self, v):
        if len(v)==0: self.v = (0,0)
        else: self.v = v

and one of my functions (add) within the class isn't returning the values I would like it to. Currently I have it defined as:

for i in range(self.dim()):
    newvector.append(self[i+1] + other[i+1])
return Vector

and I also tried:

def __add__(self, other):
    for i in range(len(self)):
        added = tuple( a + b for a, b in zip(self, other) )
    return Vector(*added)

but this returns and Unsupported Operand Type error.

The test I'd like it to pass is str(v1 + v2) == 'Vector: [3, 5, 7]' however it's returning 'Vector: [2, 3, 4, 1, 2, 3]'

Upvotes: 0

Views: 1647

Answers (1)

Guillaume Jacquenot
Guillaume Jacquenot

Reputation: 11717

You can try:

class Vector:
    def __init__(self, v):
        if len(v)==0: self.v = (0,0)
        else: self.v = v
    def __str__(self):
        return 'Vector '+' '.join([str(v) for v in self.v])
    def __add__(self, other):
        return Vector(list([a + b for a, b in zip(self.v, other.v)]))
v1=Vector((1,2,3))
v2=Vector((4,5,6))
str(v1+v2)

Upvotes: 1

Related Questions