Update lib.py

providing default value to components parameter of  __init__()
This commit is contained in:
Ashwek Swamy 2018-11-12 23:33:22 +05:30 committed by GitHub
parent 63b2c4efe0
commit b2b34e2cda
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -45,7 +45,7 @@ class Vector(object):
changeComponent(pos,value) : changes the specified component. changeComponent(pos,value) : changes the specified component.
TODO: compare-operator TODO: compare-operator
""" """
def __init__(self,components): def __init__(self,components=[]):
""" """
input: components or nothing input: components or nothing
simple constructor for init the vector simple constructor for init the vector
@ -95,13 +95,11 @@ class Vector(object):
returns a new vector that represents the sum. returns a new vector that represents the sum.
""" """
size = len(self) size = len(self)
result = []
if size == len(other): if size == len(other):
for i in range(size): result = [self.__components[i] + other.component(i) for i in range(size)]
result.append(self.__components[i] + other.component(i)) return Vector(result)
else: else:
raise Exception("must have the same size") raise Exception("must have the same size")
return Vector(result)
def __sub__(self,other): def __sub__(self,other):
""" """
input: other vector input: other vector
@ -109,22 +107,19 @@ class Vector(object):
returns a new vector that represents the differenz. returns a new vector that represents the differenz.
""" """
size = len(self) size = len(self)
result = []
if size == len(other): if size == len(other):
for i in range(size): result = [self.__components[i] - other.component(i) for i in range(size)]
result.append(self.__components[i] - other.component(i)) return result
else: # error case else: # error case
raise Exception("must have the same size") raise Exception("must have the same size")
return Vector(result)
def __mul__(self,other): def __mul__(self,other):
""" """
mul implements the scalar multiplication mul implements the scalar multiplication
and the dot-product and the dot-product
""" """
ans = []
if isinstance(other,float) or isinstance(other,int): if isinstance(other,float) or isinstance(other,int):
for c in self.__components: ans = [c*other for c in self.__components]
ans.append(c*other) return ans
elif (isinstance(other,Vector) and (len(self) == len(other))): elif (isinstance(other,Vector) and (len(self) == len(other))):
size = len(self) size = len(self)
summe = 0 summe = 0
@ -133,7 +128,6 @@ class Vector(object):
return summe return summe
else: # error case else: # error case
raise Exception("invalide operand!") raise Exception("invalide operand!")
return Vector(ans)
def copy(self): def copy(self):
""" """
copies this vector and returns it. copies this vector and returns it.