Update lib.py

replaced size() with __len__ built-in
changed self.__components = components to self.__components = list(components)
replacing for loops with list comprehension
allowing -ve indexing in component() and changeComponent()
This commit is contained in:
Ashwek Swamy 2018-11-12 23:08:07 +05:30 committed by GitHub
parent 70a6d98e0f
commit 63b2c4efe0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -36,7 +36,7 @@ class Vector(object):
set(components : list) : changes the vector components. set(components : list) : changes the vector components.
__str__() : toString method __str__() : toString method
component(i : int): gets the i-th component (start by 0) component(i : int): gets the i-th component (start by 0)
size() : gets the size of the vector (number of components) __len__() : gets the size of the vector (number of components)
euclidLength() : returns the eulidean length of the vector. euclidLength() : returns the eulidean length of the vector.
operator + : vector addition operator + : vector addition
operator - : vector subtraction operator - : vector subtraction
@ -50,7 +50,7 @@ class Vector(object):
input: components or nothing input: components or nothing
simple constructor for init the vector simple constructor for init the vector
""" """
self.__components = components self.__components = list(components)
def set(self,components): def set(self,components):
""" """
input: new components input: new components
@ -58,33 +58,24 @@ class Vector(object):
replace the components with newer one. replace the components with newer one.
""" """
if len(components) > 0: if len(components) > 0:
self.__components = components self.__components = list(components)
else: else:
raise Exception("please give any vector") raise Exception("please give any vector")
def __str__(self): def __str__(self):
""" """
returns a string representation of the vector returns a string representation of the vector
""" """
ans = "(" return "(" + ",".join(map(str, self.__components)) + ")"
length = len(self.__components)
for i in range(length):
if i != length-1:
ans += str(self.__components[i]) + ","
else:
ans += str(self.__components[i]) + ")"
if len(ans) == 1:
ans += ")"
return ans
def component(self,i): def component(self,i):
""" """
input: index (start at 0) input: index (start at 0)
output: the i-th component of the vector. output: the i-th component of the vector.
""" """
if i < len(self.__components) and i >= 0: if type(i) is int and -len(self.__components) <= i < len(self.__components) :
return self.__components[i] return self.__components[i]
else: else:
raise Exception("index out of range") raise Exception("index out of range")
def size(self): def __len__(self):
""" """
returns the size of the vector returns the size of the vector
""" """
@ -103,9 +94,9 @@ class Vector(object):
assumes: other vector has the same size assumes: other vector has the same size
returns a new vector that represents the sum. returns a new vector that represents the sum.
""" """
size = self.size() size = len(self)
result = [] result = []
if size == other.size(): if size == len(other):
for i in range(size): for i in range(size):
result.append(self.__components[i] + other.component(i)) result.append(self.__components[i] + other.component(i))
else: else:
@ -117,9 +108,9 @@ class Vector(object):
assumes: other vector has the same size assumes: other vector has the same size
returns a new vector that represents the differenz. returns a new vector that represents the differenz.
""" """
size = self.size() size = len(self)
result = [] result = []
if size == other.size(): if size == len(other):
for i in range(size): for i in range(size):
result.append(self.__components[i] - other.component(i)) result.append(self.__components[i] - other.component(i))
else: # error case else: # error case
@ -134,8 +125,8 @@ class Vector(object):
if isinstance(other,float) or isinstance(other,int): if isinstance(other,float) or isinstance(other,int):
for c in self.__components: for c in self.__components:
ans.append(c*other) ans.append(c*other)
elif (isinstance(other,Vector) and (self.size() == other.size())): elif (isinstance(other,Vector) and (len(self) == len(other))):
size = self.size() size = len(self)
summe = 0 summe = 0
for i in range(size): for i in range(size):
summe += self.__components[i] * other.component(i) summe += self.__components[i] * other.component(i)
@ -147,8 +138,7 @@ class Vector(object):
""" """
copies this vector and returns it. copies this vector and returns it.
""" """
components = [x for x in self.__components] return Vector(self.__components)
return Vector(components)
def changeComponent(self,pos,value): def changeComponent(self,pos,value):
""" """
input: an index (pos) and a value input: an index (pos) and a value
@ -156,7 +146,7 @@ class Vector(object):
'value' 'value'
""" """
#precondition #precondition
assert (pos >= 0 and pos < len(self.__components)) assert (-len(self.__components) <= pos < len(self.__components))
self.__components[pos] = value self.__components[pos] = value
def zeroVector(dimension): def zeroVector(dimension):
@ -165,10 +155,7 @@ def zeroVector(dimension):
""" """
#precondition #precondition
assert(isinstance(dimension,int)) assert(isinstance(dimension,int))
ans = [] return Vector([0]*dimension)
for i in range(dimension):
ans.append(0)
return Vector(ans)
def unitBasisVector(dimension,pos): def unitBasisVector(dimension,pos):
@ -178,12 +165,8 @@ def unitBasisVector(dimension,pos):
""" """
#precondition #precondition
assert(isinstance(dimension,int) and (isinstance(pos,int))) assert(isinstance(dimension,int) and (isinstance(pos,int)))
ans = [] ans = [0]*dimension
for i in range(dimension): ans[pos] = 1
if i != pos:
ans.append(0)
else:
ans.append(1)
return Vector(ans) return Vector(ans)
@ -206,11 +189,9 @@ def randomVector(N,a,b):
output: returns a random vector of size N, with output: returns a random vector of size N, with
random integer components between 'a' and 'b'. random integer components between 'a' and 'b'.
""" """
ans = zeroVector(N)
random.seed(None) random.seed(None)
for i in range(N): ans = [random.randint(a,b) for i in range(N)]
ans.changeComponent(i,random.randint(a,b)) return Vector(ans)
return ans
class Matrix(object): class Matrix(object):
@ -220,7 +201,7 @@ class Matrix(object):
Overview about the methods: Overview about the methods:
__str__() : returns a string representation __str__() : returns a string representation
operator * : implements the matrix vector multiplication operator * : implements the matrix vector multiplication
implements the matrix-scalar multiplication. implements the matrix-scalar multiplication.
changeComponent(x,y,value) : changes the specified component. changeComponent(x,y,value) : changes the specified component.
@ -284,7 +265,7 @@ class Matrix(object):
implements the matrix-scalar multiplication implements the matrix-scalar multiplication
""" """
if isinstance(other, Vector): # vector-matrix if isinstance(other, Vector): # vector-matrix
if (other.size() == self.__width): if (len(other) == self.__width):
ans = zeroVector(self.__height) ans = zeroVector(self.__height)
for i in range(self.__height): for i in range(self.__height):
summe = 0 summe = 0
@ -294,15 +275,9 @@ class Matrix(object):
summe = 0 summe = 0
return ans return ans
else: else:
raise Exception("vector must have the same size as the " raise Exception("vector must have the same size as the " + "number of columns of the matrix!")
+ "number of columns of the matrix!")
elif isinstance(other,int) or isinstance(other,float): # matrix-scalar elif isinstance(other,int) or isinstance(other,float): # matrix-scalar
matrix = [] matrix = [[self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height)]
for i in range(self.__height):
row = []
for j in range(self.__width):
row.append(self.__matrix[i][j] * other)
matrix.append(row)
return Matrix(matrix,self.__width,self.__height) return Matrix(matrix,self.__width,self.__height)
def __add__(self,other): def __add__(self,other):
""" """
@ -338,12 +313,7 @@ def squareZeroMatrix(N):
""" """
returns a square zero-matrix of dimension NxN returns a square zero-matrix of dimension NxN
""" """
ans = [] ans = [[0]*N for i in range(N)]
for i in range(N):
row = []
for j in range(N):
row.append(0)
ans.append(row)
return Matrix(ans,N,N) return Matrix(ans,N,N)
@ -352,13 +322,8 @@ def randomMatrix(W,H,a,b):
returns a random matrix WxH with integer components returns a random matrix WxH with integer components
between 'a' and 'b' between 'a' and 'b'
""" """
matrix = []
random.seed(None) random.seed(None)
for i in range(H): matrix = [[random.randint(a,b) for j in range(W)] for i in range(H)]
row = []
for j in range(W):
row.append(random.randint(a,b))
matrix.append(row)
return Matrix(matrix,W,H) return Matrix(matrix,W,H)