Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I add two vectors created by a class to eachother?

I have to add vector b to vector a. My class looks like this:

class Vector:
    """
    creates a vector, which can be indexed, changed and added to another vector.
    """
    def __init__(self,n=0,vec=[]):
        """
        creating vecor
        """
        self.n=n
        self.vec=list(vec)
        if len(vec)==0:
            for i in range(n):
                self.vec.append(0)
    def __getitem__(self,i):
        """
        indexing
        """
        if i>=len(self.vec):
            return(None)
        else:
            return(self.vec[i])
    def __setitem__(self,i,val):
        """
        changing
        """
        self.vec[i]=val

I tried adding another method to my class called add:

def add(a,b):
        """
        adds vector b to a
        """
        x=0
        for i in b:
            a[x]=a[x]+i
            x+=1
        return (a)
                

Lets say I want this to work:
a = Vector(vec = [1, 2, 3])
b = Vector(vec = [3, 4, 5])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

c = Vector.add(a, b)

>Solution :

What it looks like you’re trying to do make a classmethod.

Something like this should work:

@classmethod
def add(cls, a,b):
    """
    adds vector b to a
    """
    return cls(vec=[x + y for x, y in zip(a.vec, b.vec)])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading