Python Forum
Issue with def norm in class Vector - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Issue with def norm in class Vector (/thread-25314.html)



Issue with def norm in class Vector - DimosG - Mar-26-2020

Hi guys I am trying to calculate the norm(magnitude) of a Vector using class and when i run the code I get:
Error:
return math.sqrt(sum( i**2 for i in self )) TypeError: 'Vector' object is not iterable
import math

x = 2.
y = 8.
z = 6.


class Vector(object):
    def __init__(self, data):
        self.data = data
        self.rows = len(data)
    
    def __mul__(self, other):
        assert len(self.data) == len(other.data)
        result = 0.
        for vi, vj in zip(self.data, other.data):
            result += vi * vj
        return result

    def __rmul__(self, a):
        data = [a * d for d in self.data]
        return Vector(data)

    def __add__(self, other):
        assert len(self.data) == len(other.data)
        data = [i + j for (i, j) in zip(self.data, other.data)]
        return Vector(data)
    
    def norm(self):
        return math.sqrt(sum( i**2 for i in self ))
        
    def __sub__(self, other):
        assert len(self.data) == len(other.data)
        data = [i - j for (i, j) in zip(self.data, other.data)]
        return Vector(data)
    
    def __str__(self):
        return '{0}'.format(self.data)

I = Vector([1., 1., 1.])
v = Vector([1. + x, 2. + y, 3. + z])
w = Vector([4. + x, 5. + y, 6. + z])
Final = ( 2 * v - w ) + w.norm() * I
print(Final.data)



RE: Issue with def norm in class Vector - buran - Mar-26-2020

maybe you mean self.data?


RE: Issue with def norm in class Vector - stullis - Mar-26-2020

Presumably, you want to iterate over the data attribute.

    def norm(self):
        return math.sqrt(sum( i**2 for i in self.data ))



RE: Issue with def norm in class Vector - buran - Mar-26-2020

As a side note - you have Vector.rows but never use it. Instead you continue to use len(self.data) and len(other.data)

You may want to use @property

@property
def rows(self):
    return len(self.data)
then
assert self.rows == other.rows
and you are certain that self.rows will always yield the correct len


RE: Issue with def norm in class Vector - DimosG - Mar-26-2020

Wow guys thanks a lot I am new to python and classes seem a bit strange to understand !