68 lines
1.5 KiB
Python
68 lines
1.5 KiB
Python
# -*- coding: iso-8859-15 -*
|
|
from math import sqrt
|
|
import pdb
|
|
|
|
class Vector(object):
|
|
def __init__(self, coordinates):
|
|
try:
|
|
if not coordinates:
|
|
raise ValueError
|
|
self.coordinates = tuple(coordinates)
|
|
self.dimension = len(coordinates)
|
|
|
|
except ValueError:
|
|
raise ValueError('Die Koordinaten dürfen nicht leer sein')
|
|
|
|
except TypeError:
|
|
raise TypeError('Die Koordinaten müssen iterierbar sein')
|
|
|
|
|
|
def __str__(self):
|
|
return 'Vector: {}'.format(self.coordinates)
|
|
|
|
|
|
def __eq__(self, v):
|
|
return self.coordinates == v.coordinates
|
|
|
|
def plus(self,v):
|
|
new_coordinates = [x+y for x,y in zip(self.coordinates, v.coordinates)]
|
|
return Vector(new_coordinates)
|
|
|
|
#def plus(self,v):
|
|
# new_coordinates =[]
|
|
# n = len(self.coordinates)
|
|
# for i in range(n):
|
|
# new_coordinates.append(self.coordinates[i] + v.coordinates[i])
|
|
|
|
def minus(self,v):
|
|
new_coordinates = [x-y for x,y in zip(self.coordinates, v.coordinates)]
|
|
return Vector(new_coordinates)
|
|
|
|
def times_scalar(self, c):
|
|
new_coordinates = [c*x for x in self.coordinates]
|
|
return Vector(new_coordinates)
|
|
|
|
def magnitude(self):
|
|
#Länge
|
|
coordinates_squared = [x**2 for x in self.coordinates]
|
|
#pdb.set_trace()
|
|
return sqrt(sum(coordinates_squared))
|
|
|
|
def normalized(self):
|
|
try:
|
|
magnitude = self.magnitude()
|
|
return self.times_scalar(1./magnitude)
|
|
except ZeroDivisonError:
|
|
raise Exception('Ein Null-Vektor kann nicht normalisiert werden')
|
|
|
|
# Tests
|
|
|
|
|
|
veka1 = Vector([0,5])
|
|
veka2 = Vector([2,2])
|
|
|
|
print (veka1.plus(veka2))
|
|
|
|
|
|
|