Skip to content

Commit 0d5fd4a

Browse files
committed
Merge branch 'Update-linear_algebra_python' of git://github.com/ashwek/Python-1 into ashwek-Update-linear_algebra_python
2 parents 5729424 + 737bb2c commit 0d5fd4a

File tree

3 files changed

+54
-93
lines changed

3 files changed

+54
-93
lines changed

linear_algebra_python/README.md

+5-3
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ This module contains some useful classes and functions for dealing with linear a
1313

1414
- constructor(components : list) : init the vector
1515
- set(components : list) : changes the vector components.
16-
- __str__() : toString method
16+
- \_\_str\_\_() : toString method
1717
- component(i : int): gets the i-th component (start by 0)
18-
- size() : gets the size of the vector (number of components)
18+
- \_\_len\_\_() : gets the size / length of the vector (number of components)
1919
- euclidLength() : returns the eulidean length of the vector.
2020
- operator + : vector addition
2121
- operator - : vector subtraction
@@ -31,12 +31,13 @@ This module contains some useful classes and functions for dealing with linear a
3131
- computes the axpy operation
3232
- function randomVector(N,a,b)
3333
- returns a random vector of size N, with random integer components between 'a' and 'b'.
34+
3435
- class Matrix
3536
- This class represents a matrix of arbitrary size and operations on it.
3637

3738
**Overview about the methods:**
3839

39-
- __str__() : returns a string representation
40+
- \_\_str\_\_() : returns a string representation
4041
- operator * : implements the matrix vector multiplication
4142
implements the matrix-scalar multiplication.
4243
- changeComponent(x,y,value) : changes the specified component.
@@ -45,6 +46,7 @@ This module contains some useful classes and functions for dealing with linear a
4546
- height() : returns the height of the matrix
4647
- operator + : implements the matrix-addition.
4748
- operator - _ implements the matrix-subtraction
49+
4850
- function squareZeroMatrix(N)
4951
- returns a square zero-matrix of dimension NxN
5052
- function randomMatrix(W,H,a,b)

linear_algebra_python/src/lib.py

+33-74
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
@@ -45,46 +45,37 @@ class Vector(object):
4545
changeComponent(pos,value) : changes the specified component.
4646
TODO: compare-operator
4747
"""
48-
def __init__(self,components):
48+
def __init__(self,components=[]):
4949
"""
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,60 +94,53 @@ 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()
107-
result = []
108-
if size == other.size():
109-
for i in range(size):
110-
result.append(self.__components[i] + other.component(i))
97+
size = len(self)
98+
if size == len(other):
99+
result = [self.__components[i] + other.component(i) for i in range(size)]
100+
return Vector(result)
111101
else:
112102
raise Exception("must have the same size")
113-
return Vector(result)
114103
def __sub__(self,other):
115104
"""
116105
input: other vector
117106
assumes: other vector has the same size
118107
returns a new vector that represents the differenz.
119108
"""
120-
size = self.size()
121-
result = []
122-
if size == other.size():
123-
for i in range(size):
124-
result.append(self.__components[i] - other.component(i))
109+
size = len(self)
110+
if size == len(other):
111+
result = [self.__components[i] - other.component(i) for i in range(size)]
112+
return result
125113
else: # error case
126114
raise Exception("must have the same size")
127-
return Vector(result)
128115
def __mul__(self,other):
129116
"""
130117
mul implements the scalar multiplication
131118
and the dot-product
132119
"""
133-
ans = []
134120
if isinstance(other,float) or isinstance(other,int):
135-
for c in self.__components:
136-
ans.append(c*other)
137-
elif (isinstance(other,Vector) and (self.size() == other.size())):
138-
size = self.size()
121+
ans = [c*other for c in self.__components]
122+
return ans
123+
elif (isinstance(other,Vector) and (len(self) == len(other))):
124+
size = len(self)
139125
summe = 0
140126
for i in range(size):
141127
summe += self.__components[i] * other.component(i)
142128
return summe
143129
else: # error case
144130
raise Exception("invalide operand!")
145-
return Vector(ans)
146131
def copy(self):
147132
"""
148133
copies this vector and returns it.
149134
"""
150-
components = [x for x in self.__components]
151-
return Vector(components)
135+
return Vector(self.__components)
152136
def changeComponent(self,pos,value):
153137
"""
154138
input: an index (pos) and a value
155139
changes the specified component (pos) with the
156140
'value'
157141
"""
158142
#precondition
159-
assert (pos >= 0 and pos < len(self.__components))
143+
assert (-len(self.__components) <= pos < len(self.__components))
160144
self.__components[pos] = value
161145

162146
def zeroVector(dimension):
@@ -165,10 +149,7 @@ def zeroVector(dimension):
165149
"""
166150
#precondition
167151
assert(isinstance(dimension,int))
168-
ans = []
169-
for i in range(dimension):
170-
ans.append(0)
171-
return Vector(ans)
152+
return Vector([0]*dimension)
172153

173154

174155
def unitBasisVector(dimension,pos):
@@ -178,12 +159,8 @@ def unitBasisVector(dimension,pos):
178159
"""
179160
#precondition
180161
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)
162+
ans = [0]*dimension
163+
ans[pos] = 1
187164
return Vector(ans)
188165

189166

@@ -206,11 +183,9 @@ def randomVector(N,a,b):
206183
output: returns a random vector of size N, with
207184
random integer components between 'a' and 'b'.
208185
"""
209-
ans = zeroVector(N)
210186
random.seed(None)
211-
for i in range(N):
212-
ans.changeComponent(i,random.randint(a,b))
213-
return ans
187+
ans = [random.randint(a,b) for i in range(N)]
188+
return Vector(ans)
214189

215190

216191
class Matrix(object):
@@ -220,7 +195,7 @@ class Matrix(object):
220195
221196
Overview about the methods:
222197
223-
__str__() : returns a string representation
198+
__str__() : returns a string representation
224199
operator * : implements the matrix vector multiplication
225200
implements the matrix-scalar multiplication.
226201
changeComponent(x,y,value) : changes the specified component.
@@ -284,7 +259,7 @@ def __mul__(self,other):
284259
implements the matrix-scalar multiplication
285260
"""
286261
if isinstance(other, Vector): # vector-matrix
287-
if (other.size() == self.__width):
262+
if (len(other) == self.__width):
288263
ans = zeroVector(self.__height)
289264
for i in range(self.__height):
290265
summe = 0
@@ -294,15 +269,9 @@ def __mul__(self,other):
294269
summe = 0
295270
return ans
296271
else:
297-
raise Exception("vector must have the same size as the "
298-
+ "number of columns of the matrix!")
272+
raise Exception("vector must have the same size as the " + "number of columns of the matrix!")
299273
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)
274+
matrix = [[self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height)]
306275
return Matrix(matrix,self.__width,self.__height)
307276
def __add__(self,other):
308277
"""
@@ -338,12 +307,7 @@ def squareZeroMatrix(N):
338307
"""
339308
returns a square zero-matrix of dimension NxN
340309
"""
341-
ans = []
342-
for i in range(N):
343-
row = []
344-
for j in range(N):
345-
row.append(0)
346-
ans.append(row)
310+
ans = [[0]*N for i in range(N)]
347311
return Matrix(ans,N,N)
348312

349313

@@ -352,13 +316,8 @@ def randomMatrix(W,H,a,b):
352316
returns a random matrix WxH with integer components
353317
between 'a' and 'b'
354318
"""
355-
matrix = []
356319
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)
320+
matrix = [[random.randint(a,b) for j in range(W)] for i in range(H)]
362321
return Matrix(matrix,W,H)
363322

364-
323+

linear_algebra_python/src/tests.py

+16-16
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,13 @@ def test_str(self):
2929
test for toString() method
3030
"""
3131
x = Vector([0,0,0,0,0,1])
32-
self.assertEqual(x.__str__(),"(0,0,0,0,0,1)")
32+
self.assertEqual(str(x),"(0,0,0,0,0,1)")
3333
def test_size(self):
3434
"""
3535
test for size()-method
3636
"""
3737
x = Vector([1,2,3,4])
38-
self.assertEqual(x.size(),4)
38+
self.assertEqual(len(x),4)
3939
def test_euclidLength(self):
4040
"""
4141
test for the eulidean length
@@ -67,67 +67,67 @@ def test_mul(self):
6767
x = Vector([1,2,3])
6868
a = Vector([2,-1,4]) # for test of dot-product
6969
b = Vector([1,-2,-1])
70-
self.assertEqual((x*3.0).__str__(),"(3.0,6.0,9.0)")
70+
self.assertEqual(str(x*3.0),"(3.0,6.0,9.0)")
7171
self.assertEqual((a*b),0)
7272
def test_zeroVector(self):
7373
"""
7474
test for the global function zeroVector(...)
7575
"""
76-
self.assertTrue(zeroVector(10).__str__().count("0") == 10)
76+
self.assertTrue(str(zeroVector(10)).count("0") == 10)
7777
def test_unitBasisVector(self):
7878
"""
7979
test for the global function unitBasisVector(...)
8080
"""
81-
self.assertEqual(unitBasisVector(3,1).__str__(),"(0,1,0)")
81+
self.assertEqual(str(unitBasisVector(3,1)),"(0,1,0)")
8282
def test_axpy(self):
8383
"""
8484
test for the global function axpy(...) (operation)
8585
"""
8686
x = Vector([1,2,3])
8787
y = Vector([1,0,1])
88-
self.assertEqual(axpy(2,x,y).__str__(),"(3,4,7)")
88+
self.assertEqual(str(axpy(2,x,y)),"(3,4,7)")
8989
def test_copy(self):
9090
"""
9191
test for the copy()-method
9292
"""
9393
x = Vector([1,0,0,0,0,0])
9494
y = x.copy()
95-
self.assertEqual(x.__str__(),y.__str__())
95+
self.assertEqual(str(x),str(y))
9696
def test_changeComponent(self):
9797
"""
9898
test for the changeComponent(...)-method
9999
"""
100100
x = Vector([1,0,0])
101101
x.changeComponent(0,0)
102102
x.changeComponent(1,1)
103-
self.assertEqual(x.__str__(),"(0,1,0)")
103+
self.assertEqual(str(x),"(0,1,0)")
104104
def test_str_matrix(self):
105105
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
106-
self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n",A.__str__())
106+
self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n",str(A))
107107
def test__mul__matrix(self):
108108
A = Matrix([[1,2,3],[4,5,6],[7,8,9]],3,3)
109109
x = Vector([1,2,3])
110-
self.assertEqual("(14,32,50)",(A*x).__str__())
111-
self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n",(A*2).__str__())
110+
self.assertEqual("(14,32,50)",str(A*x))
111+
self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n",str(A*2))
112112
def test_changeComponent_matrix(self):
113113
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
114114
A.changeComponent(0,2,5)
115-
self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n",A.__str__())
115+
self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n",str(A))
116116
def test_component_matrix(self):
117117
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
118118
self.assertEqual(7,A.component(2,1),0.01)
119119
def test__add__matrix(self):
120120
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
121121
B = Matrix([[1,2,7],[2,4,5],[6,7,10]],3,3)
122-
self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n",(A+B).__str__())
122+
self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n",str(A+B))
123123
def test__sub__matrix(self):
124124
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
125125
B = Matrix([[1,2,7],[2,4,5],[6,7,10]],3,3)
126-
self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n",(A-B).__str__())
126+
self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n",str(A-B))
127127
def test_squareZeroMatrix(self):
128128
self.assertEqual('|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|'
129-
+'\n|0,0,0,0,0|\n',squareZeroMatrix(5).__str__())
129+
+'\n|0,0,0,0,0|\n',str(squareZeroMatrix(5)))
130130

131131

132132
if __name__ == "__main__":
133-
unittest.main()
133+
unittest.main()

0 commit comments

Comments
 (0)