2 years ago
#12455
Justimportant
How do I implement an __add__ function in a class for n-Dimensional vectors?
I am trying to create a simple class for n-dimensional vectors, but I cannot figure out how to add 2 vectors with n arguments together. I cannot find a way to return a variable amount of arguments in the __add__
function. In specific dimensions, this isn't too hard. Here's what it would look like for 2 dimensions:
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '({:g} , {:g} )'.format(self.x, self.y)
def __add__(self, other):
return Vector2D(self.x + other.x, self.y + other.y)
v, w = Vector2D(1,2), Vector2D(1,1)
print(v+w) #this should return (2, 3 )
Now I'd like to generalize this class to include all dimensions. I would probably use *args
instead of x and y. Here's what that would sort of look like:
class Vector:
def __init__(self, *args):
self.args = args
def __str__(self):#not terribly important, but this function is quite ugly
string = '( '
for i in self.args:
string += str(i)
string += ', '
string += ')'
return string
def __add__(self, other): #how would one do this?
pass
v, w = Vector(2,3,4), Vector(1,1,1)
print(v+w) #I want this to return (3, 4, 5, )
I came up with some sort of solution, but it's not terribly efficient. Instead of loose argument, this version of my class uses a single list. I find this unsatisfactory however, so I came here to ask for a better solution. I have shared my mediocre solution down below:
class Vector:
def __init__(self, list = []):
self.list = list
def __str__(self):
string = '('
for i in self.list:
string += str(i)
string += ', '
string += ')'
return string
def __add__(self, other):
if len(self.list) == len(other.list):
coordinates = []
dimension = len(self.list)
for i in range(dimension):
newcoordinate = self.list[i] + other.list[i]
coordinates.append(newcoordinate)
return Vector(coordinates)
else:
raise TypeError('Can only add vectors of the same dimension.')
v, w = Vector([2,3,4]), Vector([1,1,1])
print(v+w) #this should return (3, 4, 5, )
In summary, I don't want to have to put the coordinates of a vector in a list. I can't think of a way to implement an __add__
function though.
python
class
vector
add
args
0 Answers
Your Answer