Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit fe5c711

Browse files
tianyizheng02poyea
andauthoredOct 27, 2021
Rewrite parts of Vector and Matrix (TheAlgorithms#5362)
* Rewrite parts of Vector and Matrix methods * Refactor determinant method and add unit tests Refactor determinant method to create separate minor and cofactor methods. Add respective unit tests for new methods. Rename methods using snake case to follow Python naming conventions. * Reorganize Vector and Matrix methods * Update linear_algebra/README.md Co-authored-by: John Law <[email protected]> * Fix punctuation and wording * Apply suggestions from code review Co-authored-by: John Law <[email protected]> Co-authored-by: John Law <[email protected]>
1 parent 8285913 commit fe5c711

File tree

4 files changed

+295
-225
lines changed

4 files changed

+295
-225
lines changed
 

‎knapsack/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ The knapsack problem has been studied for more than a century, with early works
1717
## Documentation
1818

1919
This module uses docstrings to enable the use of Python's in-built `help(...)` function.
20-
For instance, try `help(Vector)`, `help(unitBasisVector)`, and `help(CLASSNAME.METHODNAME)`.
20+
For instance, try `help(Vector)`, `help(unit_basis_vector)`, and `help(CLASSNAME.METHODNAME)`.
2121

2222
---
2323

‎linear_algebra/README.md

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -10,56 +10,56 @@ This module contains classes and functions for doing linear algebra.
1010
-
1111
- This class represents a vector of arbitrary size and related operations.
1212

13-
**Overview about the methods:**
13+
**Overview of the methods:**
1414

15-
- constructor(components : list) : init the vector
16-
- set(components : list) : changes the vector components.
15+
- constructor(components) : init the vector
16+
- set(components) : changes the vector components.
1717
- \_\_str\_\_() : toString method
18-
- component(i : int): gets the i-th component (start by 0)
18+
- component(i): gets the i-th component (0-indexed)
1919
- \_\_len\_\_() : gets the size / length of the vector (number of components)
20-
- euclidLength() : returns the eulidean length of the vector.
20+
- euclidean_length() : returns the eulidean length of the vector
2121
- operator + : vector addition
2222
- operator - : vector subtraction
2323
- operator * : scalar multiplication and dot product
24-
- copy() : copies this vector and returns it.
25-
- changeComponent(pos,value) : changes the specified component.
24+
- copy() : copies this vector and returns it
25+
- change_component(pos,value) : changes the specified component
2626

27-
- function zeroVector(dimension)
27+
- function zero_vector(dimension)
2828
- returns a zero vector of 'dimension'
29-
- function unitBasisVector(dimension,pos)
30-
- returns a unit basis vector with a One at index 'pos' (indexing at 0)
31-
- function axpy(scalar,vector1,vector2)
29+
- function unit_basis_vector(dimension, pos)
30+
- returns a unit basis vector with a one at index 'pos' (0-indexed)
31+
- function axpy(scalar, vector1, vector2)
3232
- computes the axpy operation
33-
- function randomVector(N,a,b)
34-
- returns a random vector of size N, with random integer components between 'a' and 'b'.
33+
- function random_vector(N, a, b)
34+
- returns a random vector of size N, with random integer components between 'a' and 'b' inclusive
3535

3636
### class Matrix
3737
-
3838
- This class represents a matrix of arbitrary size and operations on it.
3939

40-
**Overview about the methods:**
40+
**Overview of the methods:**
4141

4242
- \_\_str\_\_() : returns a string representation
4343
- operator * : implements the matrix vector multiplication
4444
implements the matrix-scalar multiplication.
45-
- changeComponent(x,y,value) : changes the specified component.
46-
- component(x,y) : returns the specified component.
45+
- change_component(x, y, value) : changes the specified component.
46+
- component(x, y) : returns the specified component.
4747
- width() : returns the width of the matrix
4848
- height() : returns the height of the matrix
49-
- determinate() : returns the determinate of the matrix if it is square
49+
- determinant() : returns the determinant of the matrix if it is square
5050
- operator + : implements the matrix-addition.
51-
- operator - _ implements the matrix-subtraction
51+
- operator - : implements the matrix-subtraction
5252

53-
- function squareZeroMatrix(N)
53+
- function square_zero_matrix(N)
5454
- returns a square zero-matrix of dimension NxN
55-
- function randomMatrix(W,H,a,b)
56-
- returns a random matrix WxH with integer components between 'a' and 'b'
55+
- function random_matrix(W, H, a, b)
56+
- returns a random matrix WxH with integer components between 'a' and 'b' inclusive
5757
---
5858

5959
## Documentation
6060

6161
This module uses docstrings to enable the use of Python's in-built `help(...)` function.
62-
For instance, try `help(Vector)`, `help(unitBasisVector)`, and `help(CLASSNAME.METHODNAME)`.
62+
For instance, try `help(Vector)`, `help(unit_basis_vector)`, and `help(CLASSNAME.METHODNAME)`.
6363

6464
---
6565

‎linear_algebra/src/lib.py

Lines changed: 200 additions & 178 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@
1010
Overview:
1111
1212
- class Vector
13-
- function zeroVector(dimension)
14-
- function unitBasisVector(dimension,pos)
15-
- function axpy(scalar,vector1,vector2)
16-
- function randomVector(N,a,b)
13+
- function zero_vector(dimension)
14+
- function unit_basis_vector(dimension, pos)
15+
- function axpy(scalar, vector1, vector2)
16+
- function random_vector(N, a, b)
1717
- class Matrix
18-
- function squareZeroMatrix(N)
19-
- function randomMatrix(W,H,a,b)
18+
- function square_zero_matrix(N)
19+
- function random_matrix(W, H, a, b)
2020
"""
2121
from __future__ import annotations
2222

@@ -30,20 +30,23 @@ class Vector:
3030
This class represents a vector of arbitrary size.
3131
You need to give the vector components.
3232
33-
Overview about the methods:
34-
35-
constructor(components : list) : init the vector
36-
set(components : list) : changes the vector components.
37-
__str__() : toString method
38-
component(i : int): gets the i-th component (start by 0)
39-
__len__() : gets the size of the vector (number of components)
40-
euclidLength() : returns the euclidean length of the vector.
41-
operator + : vector addition
42-
operator - : vector subtraction
43-
operator * : scalar multiplication and dot product
44-
copy() : copies this vector and returns it.
45-
changeComponent(pos,value) : changes the specified component.
46-
TODO: compare-operator
33+
Overview of the methods:
34+
35+
__init__(components: Collection[float] | None): init the vector
36+
__len__(): gets the size of the vector (number of components)
37+
__str__(): returns a string representation
38+
__add__(other: Vector): vector addition
39+
__sub__(other: Vector): vector subtraction
40+
__mul__(other: float): scalar multiplication
41+
__mul__(other: Vector): dot product
42+
set(components: Collection[float]): changes the vector components
43+
copy(): copies this vector and returns it
44+
component(i): gets the i-th component (0-indexed)
45+
change_component(pos: int, value: float): changes specified component
46+
euclidean_length(): returns the euclidean length of the vector
47+
magnitude(): returns the magnitude of the vector
48+
angle(other: Vector, deg: bool): returns the angle between two vectors
49+
TODO: compare-operator
4750
"""
4851

4952
def __init__(self, components: Collection[float] | None = None) -> None:
@@ -55,47 +58,17 @@ def __init__(self, components: Collection[float] | None = None) -> None:
5558
components = []
5659
self.__components = list(components)
5760

58-
def set(self, components: Collection[float]) -> None:
59-
"""
60-
input: new components
61-
changes the components of the vector.
62-
replace the components with newer one.
63-
"""
64-
if len(components) > 0:
65-
self.__components = list(components)
66-
else:
67-
raise Exception("please give any vector")
68-
69-
def __str__(self) -> str:
70-
"""
71-
returns a string representation of the vector
72-
"""
73-
return "(" + ",".join(map(str, self.__components)) + ")"
74-
75-
def component(self, i: int) -> float:
76-
"""
77-
input: index (start at 0)
78-
output: the i-th component of the vector.
79-
"""
80-
if type(i) is int and -len(self.__components) <= i < len(self.__components):
81-
return self.__components[i]
82-
else:
83-
raise Exception("index out of range")
84-
8561
def __len__(self) -> int:
8662
"""
8763
returns the size of the vector
8864
"""
8965
return len(self.__components)
9066

91-
def euclidLength(self) -> float:
67+
def __str__(self) -> str:
9268
"""
93-
returns the euclidean length of the vector
69+
returns a string representation of the vector
9470
"""
95-
summe: float = 0
96-
for c in self.__components:
97-
summe += c ** 2
98-
return math.sqrt(summe)
71+
return "(" + ",".join(map(str, self.__components)) + ")"
9972

10073
def __add__(self, other: Vector) -> Vector:
10174
"""
@@ -139,15 +112,57 @@ def __mul__(self, other: float | Vector) -> float | Vector:
139112
if isinstance(other, float) or isinstance(other, int):
140113
ans = [c * other for c in self.__components]
141114
return Vector(ans)
142-
elif isinstance(other, Vector) and (len(self) == len(other)):
115+
elif isinstance(other, Vector) and len(self) == len(other):
143116
size = len(self)
144-
summe: float = 0
145-
for i in range(size):
146-
summe += self.__components[i] * other.component(i)
147-
return summe
117+
prods = [self.__components[i] * other.component(i) for i in range(size)]
118+
return sum(prods)
148119
else: # error case
149120
raise Exception("invalid operand!")
150121

122+
def set(self, components: Collection[float]) -> None:
123+
"""
124+
input: new components
125+
changes the components of the vector.
126+
replaces the components with newer one.
127+
"""
128+
if len(components) > 0:
129+
self.__components = list(components)
130+
else:
131+
raise Exception("please give any vector")
132+
133+
def copy(self) -> Vector:
134+
"""
135+
copies this vector and returns it.
136+
"""
137+
return Vector(self.__components)
138+
139+
def component(self, i: int) -> float:
140+
"""
141+
input: index (0-indexed)
142+
output: the i-th component of the vector.
143+
"""
144+
if type(i) is int and -len(self.__components) <= i < len(self.__components):
145+
return self.__components[i]
146+
else:
147+
raise Exception("index out of range")
148+
149+
def change_component(self, pos: int, value: float) -> None:
150+
"""
151+
input: an index (pos) and a value
152+
changes the specified component (pos) with the
153+
'value'
154+
"""
155+
# precondition
156+
assert -len(self.__components) <= pos < len(self.__components)
157+
self.__components[pos] = value
158+
159+
def euclidean_length(self) -> float:
160+
"""
161+
returns the euclidean length of the vector
162+
"""
163+
squares = [c ** 2 for c in self.__components]
164+
return math.sqrt(sum(squares))
165+
151166
def magnitude(self) -> float:
152167
"""
153168
Magnitude of a Vector
@@ -156,7 +171,8 @@ def magnitude(self) -> float:
156171
5.385164807134504
157172
158173
"""
159-
return sum([i ** 2 for i in self.__components]) ** (1 / 2)
174+
squares = [c ** 2 for c in self.__components]
175+
return math.sqrt(sum(squares))
160176

161177
def angle(self, other: Vector, deg: bool = False) -> float:
162178
"""
@@ -178,24 +194,8 @@ def angle(self, other: Vector, deg: bool = False) -> float:
178194
else:
179195
return math.acos(num / den)
180196

181-
def copy(self) -> Vector:
182-
"""
183-
copies this vector and returns it.
184-
"""
185-
return Vector(self.__components)
186-
187-
def changeComponent(self, pos: int, value: float) -> None:
188-
"""
189-
input: an index (pos) and a value
190-
changes the specified component (pos) with the
191-
'value'
192-
"""
193-
# precondition
194-
assert -len(self.__components) <= pos < len(self.__components)
195-
self.__components[pos] = value
196197

197-
198-
def zeroVector(dimension: int) -> Vector:
198+
def zero_vector(dimension: int) -> Vector:
199199
"""
200200
returns a zero-vector of size 'dimension'
201201
"""
@@ -204,7 +204,7 @@ def zeroVector(dimension: int) -> Vector:
204204
return Vector([0] * dimension)
205205

206206

207-
def unitBasisVector(dimension: int, pos: int) -> Vector:
207+
def unit_basis_vector(dimension: int, pos: int) -> Vector:
208208
"""
209209
returns a unit basis vector with a One
210210
at index 'pos' (indexing at 0)
@@ -225,40 +225,44 @@ def axpy(scalar: float, x: Vector, y: Vector) -> Vector:
225225
# precondition
226226
assert (
227227
isinstance(x, Vector)
228-
and (isinstance(y, Vector))
228+
and isinstance(y, Vector)
229229
and (isinstance(scalar, int) or isinstance(scalar, float))
230230
)
231231
return x * scalar + y
232232

233233

234-
def randomVector(N: int, a: int, b: int) -> Vector:
234+
def random_vector(n: int, a: int, b: int) -> Vector:
235235
"""
236236
input: size (N) of the vector.
237237
random range (a,b)
238238
output: returns a random vector of size N, with
239239
random integer components between 'a' and 'b'.
240240
"""
241241
random.seed(None)
242-
ans = [random.randint(a, b) for _ in range(N)]
242+
ans = [random.randint(a, b) for _ in range(n)]
243243
return Vector(ans)
244244

245245

246246
class Matrix:
247247
"""
248248
class: Matrix
249-
This class represents a arbitrary matrix.
250-
251-
Overview about the methods:
252-
253-
__str__() : returns a string representation
254-
operator * : implements the matrix vector multiplication
255-
implements the matrix-scalar multiplication.
256-
changeComponent(x,y,value) : changes the specified component.
257-
component(x,y) : returns the specified component.
258-
width() : returns the width of the matrix
259-
height() : returns the height of the matrix
260-
operator + : implements the matrix-addition.
261-
operator - _ implements the matrix-subtraction
249+
This class represents an arbitrary matrix.
250+
251+
Overview of the methods:
252+
253+
__init__():
254+
__str__(): returns a string representation
255+
__add__(other: Matrix): matrix addition
256+
__sub__(other: Matrix): matrix subtraction
257+
__mul__(other: float): scalar multiplication
258+
__mul__(other: Vector): vector multiplication
259+
height() : returns height
260+
width() : returns width
261+
component(x: int, y: int): returns specified component
262+
change_component(x: int, y: int, value: float): changes specified component
263+
minor(x: int, y: int): returns minor along (x, y)
264+
cofactor(x: int, y: int): returns cofactor along (x, y)
265+
determinant() : returns determinant
262266
"""
263267

264268
def __init__(self, matrix: list[list[float]], w: int, h: int) -> None:
@@ -285,62 +289,37 @@ def __str__(self) -> str:
285289
ans += str(self.__matrix[i][j]) + "|\n"
286290
return ans
287291

288-
def changeComponent(self, x: int, y: int, value: float) -> None:
289-
"""
290-
changes the x-y component of this matrix
291-
"""
292-
if 0 <= x < self.__height and 0 <= y < self.__width:
293-
self.__matrix[x][y] = value
294-
else:
295-
raise Exception("changeComponent: indices out of bounds")
296-
297-
def component(self, x: int, y: int) -> float:
292+
def __add__(self, other: Matrix) -> Matrix:
298293
"""
299-
returns the specified (x,y) component
294+
implements the matrix-addition.
300295
"""
301-
if 0 <= x < self.__height and 0 <= y < self.__width:
302-
return self.__matrix[x][y]
296+
if self.__width == other.width() and self.__height == other.height():
297+
matrix = []
298+
for i in range(self.__height):
299+
row = [
300+
self.__matrix[i][j] + other.component(i, j)
301+
for j in range(self.__width)
302+
]
303+
matrix.append(row)
304+
return Matrix(matrix, self.__width, self.__height)
303305
else:
304-
raise Exception("changeComponent: indices out of bounds")
305-
306-
def width(self) -> int:
307-
"""
308-
getter for the width
309-
"""
310-
return self.__width
306+
raise Exception("matrix must have the same dimension!")
311307

312-
def height(self) -> int:
308+
def __sub__(self, other: Matrix) -> Matrix:
313309
"""
314-
getter for the height
310+
implements the matrix-subtraction.
315311
"""
316-
return self.__height
317-
318-
def determinate(self) -> float:
319-
"""
320-
returns the determinate of an nxn matrix using Laplace expansion
321-
"""
322-
if self.__height == self.__width and self.__width >= 2:
323-
total = 0
324-
if self.__width > 2:
325-
for x in range(0, self.__width):
326-
for y in range(0, self.__height):
327-
total += (
328-
self.__matrix[x][y]
329-
* (-1) ** (x + y)
330-
* Matrix(
331-
self.__matrix[0:x] + self.__matrix[x + 1 :],
332-
self.__width - 1,
333-
self.__height - 1,
334-
).determinate()
335-
)
336-
else:
337-
return (
338-
self.__matrix[0][0] * self.__matrix[1][1]
339-
- self.__matrix[0][1] * self.__matrix[1][0]
340-
)
341-
return total
312+
if self.__width == other.width() and self.__height == other.height():
313+
matrix = []
314+
for i in range(self.__height):
315+
row = [
316+
self.__matrix[i][j] - other.component(i, j)
317+
for j in range(self.__width)
318+
]
319+
matrix.append(row)
320+
return Matrix(matrix, self.__width, self.__height)
342321
else:
343-
raise Exception("matrix is not square")
322+
raise Exception("matrices must have the same dimension!")
344323

345324
@overload
346325
def __mul__(self, other: float) -> Matrix:
@@ -355,20 +334,20 @@ def __mul__(self, other: float | Vector) -> Vector | Matrix:
355334
implements the matrix-vector multiplication.
356335
implements the matrix-scalar multiplication
357336
"""
358-
if isinstance(other, Vector): # vector-matrix
337+
if isinstance(other, Vector): # matrix-vector
359338
if len(other) == self.__width:
360-
ans = zeroVector(self.__height)
339+
ans = zero_vector(self.__height)
361340
for i in range(self.__height):
362-
summe: float = 0
363-
for j in range(self.__width):
364-
summe += other.component(j) * self.__matrix[i][j]
365-
ans.changeComponent(i, summe)
366-
summe = 0
341+
prods = [
342+
self.__matrix[i][j] * other.component(j)
343+
for j in range(self.__width)
344+
]
345+
ans.change_component(i, sum(prods))
367346
return ans
368347
else:
369348
raise Exception(
370349
"vector must have the same size as the "
371-
+ "number of columns of the matrix!"
350+
"number of columns of the matrix!"
372351
)
373352
elif isinstance(other, int) or isinstance(other, float): # matrix-scalar
374353
matrix = [
@@ -377,52 +356,95 @@ def __mul__(self, other: float | Vector) -> Vector | Matrix:
377356
]
378357
return Matrix(matrix, self.__width, self.__height)
379358

380-
def __add__(self, other: Matrix) -> Matrix:
359+
def height(self) -> int:
381360
"""
382-
implements the matrix-addition.
361+
getter for the height
383362
"""
384-
if self.__width == other.width() and self.__height == other.height():
385-
matrix = []
386-
for i in range(self.__height):
387-
row = []
388-
for j in range(self.__width):
389-
row.append(self.__matrix[i][j] + other.component(i, j))
390-
matrix.append(row)
391-
return Matrix(matrix, self.__width, self.__height)
363+
return self.__height
364+
365+
def width(self) -> int:
366+
"""
367+
getter for the width
368+
"""
369+
return self.__width
370+
371+
def component(self, x: int, y: int) -> float:
372+
"""
373+
returns the specified (x,y) component
374+
"""
375+
if 0 <= x < self.__height and 0 <= y < self.__width:
376+
return self.__matrix[x][y]
392377
else:
393-
raise Exception("matrix must have the same dimension!")
378+
raise Exception("change_component: indices out of bounds")
394379

395-
def __sub__(self, other: Matrix) -> Matrix:
380+
def change_component(self, x: int, y: int, value: float) -> None:
396381
"""
397-
implements the matrix-subtraction.
382+
changes the x-y component of this matrix
398383
"""
399-
if self.__width == other.width() and self.__height == other.height():
400-
matrix = []
401-
for i in range(self.__height):
402-
row = []
403-
for j in range(self.__width):
404-
row.append(self.__matrix[i][j] - other.component(i, j))
405-
matrix.append(row)
406-
return Matrix(matrix, self.__width, self.__height)
384+
if 0 <= x < self.__height and 0 <= y < self.__width:
385+
self.__matrix[x][y] = value
407386
else:
408-
raise Exception("matrix must have the same dimension!")
387+
raise Exception("change_component: indices out of bounds")
388+
389+
def minor(self, x: int, y: int) -> float:
390+
"""
391+
returns the minor along (x, y)
392+
"""
393+
if self.__height != self.__width:
394+
raise Exception("Matrix is not square")
395+
minor = self.__matrix[:x] + self.__matrix[x + 1 :]
396+
for i in range(len(minor)):
397+
minor[i] = minor[i][:y] + minor[i][y + 1 :]
398+
return Matrix(minor, self.__width - 1, self.__height - 1).determinant()
399+
400+
def cofactor(self, x: int, y: int) -> float:
401+
"""
402+
returns the cofactor (signed minor) along (x, y)
403+
"""
404+
if self.__height != self.__width:
405+
raise Exception("Matrix is not square")
406+
if 0 <= x < self.__height and 0 <= y < self.__width:
407+
return (-1) ** (x + y) * self.minor(x, y)
408+
else:
409+
raise Exception("Indices out of bounds")
410+
411+
def determinant(self) -> float:
412+
"""
413+
returns the determinant of an nxn matrix using Laplace expansion
414+
"""
415+
if self.__height != self.__width:
416+
raise Exception("Matrix is not square")
417+
if self.__height < 1:
418+
raise Exception("Matrix has no element")
419+
elif self.__height == 1:
420+
return self.__matrix[0][0]
421+
elif self.__height == 2:
422+
return (
423+
self.__matrix[0][0] * self.__matrix[1][1]
424+
- self.__matrix[0][1] * self.__matrix[1][0]
425+
)
426+
else:
427+
cofactor_prods = [
428+
self.__matrix[0][y] * self.cofactor(0, y) for y in range(self.__width)
429+
]
430+
return sum(cofactor_prods)
409431

410432

411-
def squareZeroMatrix(N: int) -> Matrix:
433+
def square_zero_matrix(n: int) -> Matrix:
412434
"""
413435
returns a square zero-matrix of dimension NxN
414436
"""
415-
ans: list[list[float]] = [[0] * N for _ in range(N)]
416-
return Matrix(ans, N, N)
437+
ans: list[list[float]] = [[0] * n for _ in range(n)]
438+
return Matrix(ans, n, n)
417439

418440

419-
def randomMatrix(W: int, H: int, a: int, b: int) -> Matrix:
441+
def random_matrix(width: int, height: int, a: int, b: int) -> Matrix:
420442
"""
421443
returns a random matrix WxH with integer components
422444
between 'a' and 'b'
423445
"""
424446
random.seed(None)
425447
matrix: list[list[float]] = [
426-
[random.randint(a, b) for _ in range(W)] for _ in range(H)
448+
[random.randint(a, b) for _ in range(width)] for _ in range(height)
427449
]
428-
return Matrix(matrix, W, H)
450+
return Matrix(matrix, width, height)

‎linear_algebra/src/test_linear_algebra.py

Lines changed: 72 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,20 @@
88
"""
99
import unittest
1010

11-
from .lib import Matrix, Vector, axpy, squareZeroMatrix, unitBasisVector, zeroVector
11+
from .lib import (
12+
Matrix,
13+
Vector,
14+
axpy,
15+
square_zero_matrix,
16+
unit_basis_vector,
17+
zero_vector,
18+
)
1219

1320

1421
class Test(unittest.TestCase):
1522
def test_component(self) -> None:
1623
"""
17-
test for method component
24+
test for method component()
1825
"""
1926
x = Vector([1, 2, 3])
2027
self.assertEqual(x.component(0), 1)
@@ -23,24 +30,24 @@ def test_component(self) -> None:
2330

2431
def test_str(self) -> None:
2532
"""
26-
test for toString() method
33+
test for method toString()
2734
"""
2835
x = Vector([0, 0, 0, 0, 0, 1])
2936
self.assertEqual(str(x), "(0,0,0,0,0,1)")
3037

3138
def test_size(self) -> None:
3239
"""
33-
test for size()-method
40+
test for method size()
3441
"""
3542
x = Vector([1, 2, 3, 4])
3643
self.assertEqual(len(x), 4)
3744

3845
def test_euclidLength(self) -> None:
3946
"""
40-
test for the eulidean length
47+
test for method euclidean_length()
4148
"""
4249
x = Vector([1, 2])
43-
self.assertAlmostEqual(x.euclidLength(), 2.236, 3)
50+
self.assertAlmostEqual(x.euclidean_length(), 2.236, 3)
4451

4552
def test_add(self) -> None:
4653
"""
@@ -67,88 +74,129 @@ def test_mul(self) -> None:
6774
test for * operator
6875
"""
6976
x = Vector([1, 2, 3])
70-
a = Vector([2, -1, 4]) # for test of dot-product
77+
a = Vector([2, -1, 4]) # for test of dot product
7178
b = Vector([1, -2, -1])
7279
self.assertEqual(str(x * 3.0), "(3.0,6.0,9.0)")
7380
self.assertEqual((a * b), 0)
7481

7582
def test_zeroVector(self) -> None:
7683
"""
77-
test for the global function zeroVector(...)
84+
test for global function zero_vector()
7885
"""
79-
self.assertTrue(str(zeroVector(10)).count("0") == 10)
86+
self.assertTrue(str(zero_vector(10)).count("0") == 10)
8087

8188
def test_unitBasisVector(self) -> None:
8289
"""
83-
test for the global function unitBasisVector(...)
90+
test for global function unit_basis_vector()
8491
"""
85-
self.assertEqual(str(unitBasisVector(3, 1)), "(0,1,0)")
92+
self.assertEqual(str(unit_basis_vector(3, 1)), "(0,1,0)")
8693

8794
def test_axpy(self) -> None:
8895
"""
89-
test for the global function axpy(...) (operation)
96+
test for global function axpy() (operation)
9097
"""
9198
x = Vector([1, 2, 3])
9299
y = Vector([1, 0, 1])
93100
self.assertEqual(str(axpy(2, x, y)), "(3,4,7)")
94101

95102
def test_copy(self) -> None:
96103
"""
97-
test for the copy()-method
104+
test for method copy()
98105
"""
99106
x = Vector([1, 0, 0, 0, 0, 0])
100107
y = x.copy()
101108
self.assertEqual(str(x), str(y))
102109

103110
def test_changeComponent(self) -> None:
104111
"""
105-
test for the changeComponent(...)-method
112+
test for method change_component()
106113
"""
107114
x = Vector([1, 0, 0])
108-
x.changeComponent(0, 0)
109-
x.changeComponent(1, 1)
115+
x.change_component(0, 0)
116+
x.change_component(1, 1)
110117
self.assertEqual(str(x), "(0,1,0)")
111118

112119
def test_str_matrix(self) -> None:
120+
"""
121+
test for Matrix method str()
122+
"""
113123
A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
114124
self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n", str(A))
115125

116-
def test_determinate(self) -> None:
126+
def test_minor(self) -> None:
127+
"""
128+
test for Matrix method minor()
129+
"""
130+
A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
131+
minors = [[-3, -14, -10], [-5, -10, -5], [-2, -1, 0]]
132+
for x in range(A.height()):
133+
for y in range(A.width()):
134+
self.assertEqual(minors[x][y], A.minor(x, y))
135+
136+
def test_cofactor(self) -> None:
117137
"""
118-
test for determinate()
138+
test for Matrix method cofactor()
119139
"""
120-
A = Matrix([[1, 1, 4, 5], [3, 3, 3, 2], [5, 1, 9, 0], [9, 7, 7, 9]], 4, 4)
121-
self.assertEqual(-376, A.determinate())
140+
A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
141+
cofactors = [[-3, 14, -10], [5, -10, 5], [-2, 1, 0]]
142+
for x in range(A.height()):
143+
for y in range(A.width()):
144+
self.assertEqual(cofactors[x][y], A.cofactor(x, y))
145+
146+
def test_determinant(self) -> None:
147+
"""
148+
test for Matrix method determinant()
149+
"""
150+
A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
151+
self.assertEqual(-5, A.determinant())
122152

123153
def test__mul__matrix(self) -> None:
154+
"""
155+
test for Matrix * operator
156+
"""
124157
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]], 3, 3)
125158
x = Vector([1, 2, 3])
126159
self.assertEqual("(14,32,50)", str(A * x))
127160
self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n", str(A * 2))
128161

129-
def test_changeComponent_matrix(self) -> None:
162+
def test_change_component_matrix(self) -> None:
163+
"""
164+
test for Matrix method change_component()
165+
"""
130166
A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
131-
A.changeComponent(0, 2, 5)
167+
A.change_component(0, 2, 5)
132168
self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n", str(A))
133169

134170
def test_component_matrix(self) -> None:
171+
"""
172+
test for Matrix method component()
173+
"""
135174
A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
136175
self.assertEqual(7, A.component(2, 1), 0.01)
137176

138177
def test__add__matrix(self) -> None:
178+
"""
179+
test for Matrix + operator
180+
"""
139181
A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
140182
B = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3)
141183
self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n", str(A + B))
142184

143185
def test__sub__matrix(self) -> None:
186+
"""
187+
test for Matrix - operator
188+
"""
144189
A = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]], 3, 3)
145190
B = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 10]], 3, 3)
146191
self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n", str(A - B))
147192

148193
def test_squareZeroMatrix(self) -> None:
194+
"""
195+
test for global function square_zero_matrix()
196+
"""
149197
self.assertEqual(
150-
"|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|" + "\n|0,0,0,0,0|\n",
151-
str(squareZeroMatrix(5)),
198+
"|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n",
199+
str(square_zero_matrix(5)),
152200
)
153201

154202

0 commit comments

Comments
 (0)
Please sign in to comment.