Skip to content

Commit 63b2c4e

Browse files
authored
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()
1 parent 70a6d98 commit 63b2c4e

File tree

1 file changed

+26
-61
lines changed
  • linear_algebra_python/src

1 file changed

+26
-61
lines changed

linear_algebra_python/src/lib.py

Lines changed: 26 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ class Vector(object):
3636
set(components : list) : changes the vector components.
3737
__str__() : toString method
3838
component(i : int): gets the i-th component (start by 0)
39-
size() : gets the size of the vector (number of components)
39+
__len__() : gets the size of the vector (number of components)
4040
euclidLength() : returns the eulidean length of the vector.
4141
operator + : vector addition
4242
operator - : vector subtraction
@@ -50,41 +50,32 @@ def __init__(self,components):
5050
input: components or nothing
5151
simple constructor for init the vector
5252
"""
53-
self.__components = components
53+
self.__components = list(components)
5454
def set(self,components):
5555
"""
5656
input: new components
5757
changes the components of the vector.
5858
replace the components with newer one.
5959
"""
6060
if len(components) > 0:
61-
self.__components = components
61+
self.__components = list(components)
6262
else:
6363
raise Exception("please give any vector")
6464
def __str__(self):
6565
"""
6666
returns a string representation of the vector
6767
"""
68-
ans = "("
69-
length = len(self.__components)
70-
for i in range(length):
71-
if i != length-1:
72-
ans += str(self.__components[i]) + ","
73-
else:
74-
ans += str(self.__components[i]) + ")"
75-
if len(ans) == 1:
76-
ans += ")"
77-
return ans
68+
return "(" + ",".join(map(str, self.__components)) + ")"
7869
def component(self,i):
7970
"""
8071
input: index (start at 0)
8172
output: the i-th component of the vector.
8273
"""
83-
if i < len(self.__components) and i >= 0:
74+
if type(i) is int and -len(self.__components) <= i < len(self.__components) :
8475
return self.__components[i]
8576
else:
8677
raise Exception("index out of range")
87-
def size(self):
78+
def __len__(self):
8879
"""
8980
returns the size of the vector
9081
"""
@@ -103,9 +94,9 @@ def __add__(self,other):
10394
assumes: other vector has the same size
10495
returns a new vector that represents the sum.
10596
"""
106-
size = self.size()
97+
size = len(self)
10798
result = []
108-
if size == other.size():
99+
if size == len(other):
109100
for i in range(size):
110101
result.append(self.__components[i] + other.component(i))
111102
else:
@@ -117,9 +108,9 @@ def __sub__(self,other):
117108
assumes: other vector has the same size
118109
returns a new vector that represents the differenz.
119110
"""
120-
size = self.size()
111+
size = len(self)
121112
result = []
122-
if size == other.size():
113+
if size == len(other):
123114
for i in range(size):
124115
result.append(self.__components[i] - other.component(i))
125116
else: # error case
@@ -134,8 +125,8 @@ def __mul__(self,other):
134125
if isinstance(other,float) or isinstance(other,int):
135126
for c in self.__components:
136127
ans.append(c*other)
137-
elif (isinstance(other,Vector) and (self.size() == other.size())):
138-
size = self.size()
128+
elif (isinstance(other,Vector) and (len(self) == len(other))):
129+
size = len(self)
139130
summe = 0
140131
for i in range(size):
141132
summe += self.__components[i] * other.component(i)
@@ -147,16 +138,15 @@ def copy(self):
147138
"""
148139
copies this vector and returns it.
149140
"""
150-
components = [x for x in self.__components]
151-
return Vector(components)
141+
return Vector(self.__components)
152142
def changeComponent(self,pos,value):
153143
"""
154144
input: an index (pos) and a value
155145
changes the specified component (pos) with the
156146
'value'
157147
"""
158148
#precondition
159-
assert (pos >= 0 and pos < len(self.__components))
149+
assert (-len(self.__components) <= pos < len(self.__components))
160150
self.__components[pos] = value
161151

162152
def zeroVector(dimension):
@@ -165,10 +155,7 @@ def zeroVector(dimension):
165155
"""
166156
#precondition
167157
assert(isinstance(dimension,int))
168-
ans = []
169-
for i in range(dimension):
170-
ans.append(0)
171-
return Vector(ans)
158+
return Vector([0]*dimension)
172159

173160

174161
def unitBasisVector(dimension,pos):
@@ -178,12 +165,8 @@ def unitBasisVector(dimension,pos):
178165
"""
179166
#precondition
180167
assert(isinstance(dimension,int) and (isinstance(pos,int)))
181-
ans = []
182-
for i in range(dimension):
183-
if i != pos:
184-
ans.append(0)
185-
else:
186-
ans.append(1)
168+
ans = [0]*dimension
169+
ans[pos] = 1
187170
return Vector(ans)
188171

189172

@@ -206,11 +189,9 @@ def randomVector(N,a,b):
206189
output: returns a random vector of size N, with
207190
random integer components between 'a' and 'b'.
208191
"""
209-
ans = zeroVector(N)
210192
random.seed(None)
211-
for i in range(N):
212-
ans.changeComponent(i,random.randint(a,b))
213-
return ans
193+
ans = [random.randint(a,b) for i in range(N)]
194+
return Vector(ans)
214195

215196

216197
class Matrix(object):
@@ -220,7 +201,7 @@ class Matrix(object):
220201
221202
Overview about the methods:
222203
223-
__str__() : returns a string representation
204+
__str__() : returns a string representation
224205
operator * : implements the matrix vector multiplication
225206
implements the matrix-scalar multiplication.
226207
changeComponent(x,y,value) : changes the specified component.
@@ -284,7 +265,7 @@ def __mul__(self,other):
284265
implements the matrix-scalar multiplication
285266
"""
286267
if isinstance(other, Vector): # vector-matrix
287-
if (other.size() == self.__width):
268+
if (len(other) == self.__width):
288269
ans = zeroVector(self.__height)
289270
for i in range(self.__height):
290271
summe = 0
@@ -294,15 +275,9 @@ def __mul__(self,other):
294275
summe = 0
295276
return ans
296277
else:
297-
raise Exception("vector must have the same size as the "
298-
+ "number of columns of the matrix!")
278+
raise Exception("vector must have the same size as the " + "number of columns of the matrix!")
299279
elif isinstance(other,int) or isinstance(other,float): # matrix-scalar
300-
matrix = []
301-
for i in range(self.__height):
302-
row = []
303-
for j in range(self.__width):
304-
row.append(self.__matrix[i][j] * other)
305-
matrix.append(row)
280+
matrix = [[self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height)]
306281
return Matrix(matrix,self.__width,self.__height)
307282
def __add__(self,other):
308283
"""
@@ -338,12 +313,7 @@ def squareZeroMatrix(N):
338313
"""
339314
returns a square zero-matrix of dimension NxN
340315
"""
341-
ans = []
342-
for i in range(N):
343-
row = []
344-
for j in range(N):
345-
row.append(0)
346-
ans.append(row)
316+
ans = [[0]*N for i in range(N)]
347317
return Matrix(ans,N,N)
348318

349319

@@ -352,13 +322,8 @@ def randomMatrix(W,H,a,b):
352322
returns a random matrix WxH with integer components
353323
between 'a' and 'b'
354324
"""
355-
matrix = []
356325
random.seed(None)
357-
for i in range(H):
358-
row = []
359-
for j in range(W):
360-
row.append(random.randint(a,b))
361-
matrix.append(row)
326+
matrix = [[random.randint(a,b) for j in range(W)] for i in range(H)]
362327
return Matrix(matrix,W,H)
363328

364-
329+

0 commit comments

Comments
 (0)