Skip to content

Instantly share code, notes, and snippets.

@wsricardo
Last active January 9, 2023 14:54
Show Gist options
  • Save wsricardo/c91ea0424fd288aa446b5b04b6e5ba2d to your computer and use it in GitHub Desktop.
Save wsricardo/c91ea0424fd288aa446b5b04b6e5ba2d to your computer and use it in GitHub Desktop.
Class Vector and your operations.
class Vector:
"""
Class Vector
------------
Define 'vector' object and
operations vectors.
"""
def __init__(self, values):
self.values = values
def __repr__(self):
return "\n= "+str(self.values)
def __str__(self):
return str(self.values)
def __mul__(self, other, context=None):
if not isinstance(other, self.__class__) :
print('self')
return map( lambda u: self*u, other.values )
elif isinstance(other, float):
print('other')
return map( lambda u: other*u, self.values )
else:
return sum( map( lambda v,u: u*v , self.values, other.values ) )
def __add__(self, other):
if len(self.values) != len(other.values):
raise 'Error...'
return [ self.values[i] + other.values[i] for i in range( len(u.values) ) ]
def __sub__(self, other):
return
if __name__=="__main__":
v = Vector([1, 3, 2])
u = Vector([6, 1, 2])
#print(u+v)
#print(f"{u} * {v} \n= {u*v}")
print(2*u)
@wsricardo
Copy link
Author

wsricardo commented Jan 9, 2023

Estou obterndo o erro 'TypeError: unsupported operand type(s) for *: 'int' and 'Vector''

Considerando o código na versão abaixo

class Vector:
    """
        Class Vector
        ------------

        Define 'vector' object and
        operations vectors. 
    """
    
    def __init__(self, values):
        self.values = values

    def __repr__(self):
        return "\n= "+str(self.values)

    def __str__(self):
        return str(self.values)
    
    def __mul__(self, other, context=None):
        
        if not isinstance(other, self.__class__) :
            print('self')
            return map( lambda u: self*u, other.values )
        
        elif isinstance(other, float):
            print('other')
            return map( lambda u: other*u, self.values )
        
        else:        
            return sum( map( lambda v,u: u*v , self.values, other.values ) )

    def __add__(self, other):
        if len(self.values) != len(other.values):
            raise 'Error...'
        return  [ self.values[i] + other.values[i] for i in range( len(u.values) ) ]

    def __sub__(self, other):
        return  


if __name__=="__main__":
    v = Vector([1, 3, 2])
    u = Vector([6, 1, 2])

    #print(u+v)
    
    #print(f"{u} * {v} \n= {u*v}")
    print(2*u)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment