class Vector(object):
def __init__(self,coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates=coordinates
self.dimension=len(coordinates)
except ValueError:
raise ValueError('The coordinates must be non empty')
except TypeError:
raise TypeError('The coordinates must be iterable')
def __str__(self):
return 'Vector: {}'.format(self.coordinates)
def magnitude(self):
mag = [(sum(x**2 for x in self.coordinates))**0.5]
return Vector(mag)
def normalize(self):
mag= self.magnitude()
normal= [((1/mag)*x for x in self.coordinates)]
return Vector(normal)
vector_m=Vector([5.581,-2.136])
print vector_m.normalize()
vector_m=Vector([-0.221,7.437])
print vector_m.magnitude()
答案 0 :(得分:0)
此
normal= [((1/mag)*x for x in self.coordinates)]
创建包含生成器的1元素列表。表达式
((1/mag)*x for x in self.coordinates)
是generator expression。你想要的是:
normal= [(1/mag)*x for x in self.coordinates]