mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-20 08:12:02 +00:00
Merge branch 'Update-linear_algebra_python' of git://github.com/ashwek/Python-1 into ashwek-Update-linear_algebra_python
This commit is contained in:
commit
0d5fd4a5f2
|
@ -13,9 +13,9 @@ This module contains some useful classes and functions for dealing with linear a
|
|||
|
||||
- constructor(components : list) : init the vector
|
||||
- set(components : list) : changes the vector components.
|
||||
- __str__() : toString method
|
||||
- \_\_str\_\_() : toString method
|
||||
- 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 / length of the vector (number of components)
|
||||
- euclidLength() : returns the eulidean length of the vector.
|
||||
- operator + : vector addition
|
||||
- operator - : vector subtraction
|
||||
|
@ -31,12 +31,13 @@ This module contains some useful classes and functions for dealing with linear a
|
|||
- computes the axpy operation
|
||||
- function randomVector(N,a,b)
|
||||
- returns a random vector of size N, with random integer components between 'a' and 'b'.
|
||||
|
||||
- class Matrix
|
||||
- This class represents a matrix of arbitrary size and operations on it.
|
||||
|
||||
**Overview about the methods:**
|
||||
|
||||
- __str__() : returns a string representation
|
||||
- \_\_str\_\_() : returns a string representation
|
||||
- operator * : implements the matrix vector multiplication
|
||||
implements the matrix-scalar multiplication.
|
||||
- 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
|
|||
- height() : returns the height of the matrix
|
||||
- operator + : implements the matrix-addition.
|
||||
- operator - _ implements the matrix-subtraction
|
||||
|
||||
- function squareZeroMatrix(N)
|
||||
- returns a square zero-matrix of dimension NxN
|
||||
- function randomMatrix(W,H,a,b)
|
||||
|
|
|
@ -36,7 +36,7 @@ class Vector(object):
|
|||
set(components : list) : changes the vector components.
|
||||
__str__() : toString method
|
||||
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.
|
||||
operator + : vector addition
|
||||
operator - : vector subtraction
|
||||
|
@ -45,12 +45,12 @@ class Vector(object):
|
|||
changeComponent(pos,value) : changes the specified component.
|
||||
TODO: compare-operator
|
||||
"""
|
||||
def __init__(self,components):
|
||||
def __init__(self,components=[]):
|
||||
"""
|
||||
input: components or nothing
|
||||
simple constructor for init the vector
|
||||
"""
|
||||
self.__components = components
|
||||
self.__components = list(components)
|
||||
def set(self,components):
|
||||
"""
|
||||
input: new components
|
||||
|
@ -58,33 +58,24 @@ class Vector(object):
|
|||
replace the components with newer one.
|
||||
"""
|
||||
if len(components) > 0:
|
||||
self.__components = components
|
||||
self.__components = list(components)
|
||||
else:
|
||||
raise Exception("please give any vector")
|
||||
def __str__(self):
|
||||
"""
|
||||
returns a string representation of the vector
|
||||
"""
|
||||
ans = "("
|
||||
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
|
||||
return "(" + ",".join(map(str, self.__components)) + ")"
|
||||
def component(self,i):
|
||||
"""
|
||||
input: index (start at 0)
|
||||
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]
|
||||
else:
|
||||
raise Exception("index out of range")
|
||||
def size(self):
|
||||
def __len__(self):
|
||||
"""
|
||||
returns the size of the vector
|
||||
"""
|
||||
|
@ -103,52 +94,45 @@ class Vector(object):
|
|||
assumes: other vector has the same size
|
||||
returns a new vector that represents the sum.
|
||||
"""
|
||||
size = self.size()
|
||||
result = []
|
||||
if size == other.size():
|
||||
for i in range(size):
|
||||
result.append(self.__components[i] + other.component(i))
|
||||
size = len(self)
|
||||
if size == len(other):
|
||||
result = [self.__components[i] + other.component(i) for i in range(size)]
|
||||
return Vector(result)
|
||||
else:
|
||||
raise Exception("must have the same size")
|
||||
return Vector(result)
|
||||
def __sub__(self,other):
|
||||
"""
|
||||
input: other vector
|
||||
assumes: other vector has the same size
|
||||
returns a new vector that represents the differenz.
|
||||
"""
|
||||
size = self.size()
|
||||
result = []
|
||||
if size == other.size():
|
||||
for i in range(size):
|
||||
result.append(self.__components[i] - other.component(i))
|
||||
size = len(self)
|
||||
if size == len(other):
|
||||
result = [self.__components[i] - other.component(i) for i in range(size)]
|
||||
return result
|
||||
else: # error case
|
||||
raise Exception("must have the same size")
|
||||
return Vector(result)
|
||||
def __mul__(self,other):
|
||||
"""
|
||||
mul implements the scalar multiplication
|
||||
and the dot-product
|
||||
"""
|
||||
ans = []
|
||||
if isinstance(other,float) or isinstance(other,int):
|
||||
for c in self.__components:
|
||||
ans.append(c*other)
|
||||
elif (isinstance(other,Vector) and (self.size() == other.size())):
|
||||
size = self.size()
|
||||
ans = [c*other for c in self.__components]
|
||||
return ans
|
||||
elif (isinstance(other,Vector) and (len(self) == len(other))):
|
||||
size = len(self)
|
||||
summe = 0
|
||||
for i in range(size):
|
||||
summe += self.__components[i] * other.component(i)
|
||||
return summe
|
||||
else: # error case
|
||||
raise Exception("invalide operand!")
|
||||
return Vector(ans)
|
||||
def copy(self):
|
||||
"""
|
||||
copies this vector and returns it.
|
||||
"""
|
||||
components = [x for x in self.__components]
|
||||
return Vector(components)
|
||||
return Vector(self.__components)
|
||||
def changeComponent(self,pos,value):
|
||||
"""
|
||||
input: an index (pos) and a value
|
||||
|
@ -156,7 +140,7 @@ class Vector(object):
|
|||
'value'
|
||||
"""
|
||||
#precondition
|
||||
assert (pos >= 0 and pos < len(self.__components))
|
||||
assert (-len(self.__components) <= pos < len(self.__components))
|
||||
self.__components[pos] = value
|
||||
|
||||
def zeroVector(dimension):
|
||||
|
@ -165,10 +149,7 @@ def zeroVector(dimension):
|
|||
"""
|
||||
#precondition
|
||||
assert(isinstance(dimension,int))
|
||||
ans = []
|
||||
for i in range(dimension):
|
||||
ans.append(0)
|
||||
return Vector(ans)
|
||||
return Vector([0]*dimension)
|
||||
|
||||
|
||||
def unitBasisVector(dimension,pos):
|
||||
|
@ -178,12 +159,8 @@ def unitBasisVector(dimension,pos):
|
|||
"""
|
||||
#precondition
|
||||
assert(isinstance(dimension,int) and (isinstance(pos,int)))
|
||||
ans = []
|
||||
for i in range(dimension):
|
||||
if i != pos:
|
||||
ans.append(0)
|
||||
else:
|
||||
ans.append(1)
|
||||
ans = [0]*dimension
|
||||
ans[pos] = 1
|
||||
return Vector(ans)
|
||||
|
||||
|
||||
|
@ -206,11 +183,9 @@ def randomVector(N,a,b):
|
|||
output: returns a random vector of size N, with
|
||||
random integer components between 'a' and 'b'.
|
||||
"""
|
||||
ans = zeroVector(N)
|
||||
random.seed(None)
|
||||
for i in range(N):
|
||||
ans.changeComponent(i,random.randint(a,b))
|
||||
return ans
|
||||
ans = [random.randint(a,b) for i in range(N)]
|
||||
return Vector(ans)
|
||||
|
||||
|
||||
class Matrix(object):
|
||||
|
@ -220,7 +195,7 @@ class Matrix(object):
|
|||
|
||||
Overview about the methods:
|
||||
|
||||
__str__() : returns a string representation
|
||||
__str__() : returns a string representation
|
||||
operator * : implements the matrix vector multiplication
|
||||
implements the matrix-scalar multiplication.
|
||||
changeComponent(x,y,value) : changes the specified component.
|
||||
|
@ -284,7 +259,7 @@ class Matrix(object):
|
|||
implements the matrix-scalar multiplication
|
||||
"""
|
||||
if isinstance(other, Vector): # vector-matrix
|
||||
if (other.size() == self.__width):
|
||||
if (len(other) == self.__width):
|
||||
ans = zeroVector(self.__height)
|
||||
for i in range(self.__height):
|
||||
summe = 0
|
||||
|
@ -294,15 +269,9 @@ class Matrix(object):
|
|||
summe = 0
|
||||
return ans
|
||||
else:
|
||||
raise Exception("vector must have the same size as the "
|
||||
+ "number of columns of the matrix!")
|
||||
raise Exception("vector must have the same size as the " + "number of columns of the matrix!")
|
||||
elif isinstance(other,int) or isinstance(other,float): # matrix-scalar
|
||||
matrix = []
|
||||
for i in range(self.__height):
|
||||
row = []
|
||||
for j in range(self.__width):
|
||||
row.append(self.__matrix[i][j] * other)
|
||||
matrix.append(row)
|
||||
matrix = [[self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height)]
|
||||
return Matrix(matrix,self.__width,self.__height)
|
||||
def __add__(self,other):
|
||||
"""
|
||||
|
@ -338,12 +307,7 @@ def squareZeroMatrix(N):
|
|||
"""
|
||||
returns a square zero-matrix of dimension NxN
|
||||
"""
|
||||
ans = []
|
||||
for i in range(N):
|
||||
row = []
|
||||
for j in range(N):
|
||||
row.append(0)
|
||||
ans.append(row)
|
||||
ans = [[0]*N for i in range(N)]
|
||||
return Matrix(ans,N,N)
|
||||
|
||||
|
||||
|
@ -352,13 +316,8 @@ def randomMatrix(W,H,a,b):
|
|||
returns a random matrix WxH with integer components
|
||||
between 'a' and 'b'
|
||||
"""
|
||||
matrix = []
|
||||
random.seed(None)
|
||||
for i in range(H):
|
||||
row = []
|
||||
for j in range(W):
|
||||
row.append(random.randint(a,b))
|
||||
matrix.append(row)
|
||||
matrix = [[random.randint(a,b) for j in range(W)] for i in range(H)]
|
||||
return Matrix(matrix,W,H)
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -29,13 +29,13 @@ class Test(unittest.TestCase):
|
|||
test for toString() method
|
||||
"""
|
||||
x = Vector([0,0,0,0,0,1])
|
||||
self.assertEqual(x.__str__(),"(0,0,0,0,0,1)")
|
||||
self.assertEqual(str(x),"(0,0,0,0,0,1)")
|
||||
def test_size(self):
|
||||
"""
|
||||
test for size()-method
|
||||
"""
|
||||
x = Vector([1,2,3,4])
|
||||
self.assertEqual(x.size(),4)
|
||||
self.assertEqual(len(x),4)
|
||||
def test_euclidLength(self):
|
||||
"""
|
||||
test for the eulidean length
|
||||
|
@ -67,32 +67,32 @@ class Test(unittest.TestCase):
|
|||
x = Vector([1,2,3])
|
||||
a = Vector([2,-1,4]) # for test of dot-product
|
||||
b = Vector([1,-2,-1])
|
||||
self.assertEqual((x*3.0).__str__(),"(3.0,6.0,9.0)")
|
||||
self.assertEqual(str(x*3.0),"(3.0,6.0,9.0)")
|
||||
self.assertEqual((a*b),0)
|
||||
def test_zeroVector(self):
|
||||
"""
|
||||
test for the global function zeroVector(...)
|
||||
"""
|
||||
self.assertTrue(zeroVector(10).__str__().count("0") == 10)
|
||||
self.assertTrue(str(zeroVector(10)).count("0") == 10)
|
||||
def test_unitBasisVector(self):
|
||||
"""
|
||||
test for the global function unitBasisVector(...)
|
||||
"""
|
||||
self.assertEqual(unitBasisVector(3,1).__str__(),"(0,1,0)")
|
||||
self.assertEqual(str(unitBasisVector(3,1)),"(0,1,0)")
|
||||
def test_axpy(self):
|
||||
"""
|
||||
test for the global function axpy(...) (operation)
|
||||
"""
|
||||
x = Vector([1,2,3])
|
||||
y = Vector([1,0,1])
|
||||
self.assertEqual(axpy(2,x,y).__str__(),"(3,4,7)")
|
||||
self.assertEqual(str(axpy(2,x,y)),"(3,4,7)")
|
||||
def test_copy(self):
|
||||
"""
|
||||
test for the copy()-method
|
||||
"""
|
||||
x = Vector([1,0,0,0,0,0])
|
||||
y = x.copy()
|
||||
self.assertEqual(x.__str__(),y.__str__())
|
||||
self.assertEqual(str(x),str(y))
|
||||
def test_changeComponent(self):
|
||||
"""
|
||||
test for the changeComponent(...)-method
|
||||
|
@ -100,34 +100,34 @@ class Test(unittest.TestCase):
|
|||
x = Vector([1,0,0])
|
||||
x.changeComponent(0,0)
|
||||
x.changeComponent(1,1)
|
||||
self.assertEqual(x.__str__(),"(0,1,0)")
|
||||
self.assertEqual(str(x),"(0,1,0)")
|
||||
def test_str_matrix(self):
|
||||
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
||||
self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n",A.__str__())
|
||||
self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n",str(A))
|
||||
def test__mul__matrix(self):
|
||||
A = Matrix([[1,2,3],[4,5,6],[7,8,9]],3,3)
|
||||
x = Vector([1,2,3])
|
||||
self.assertEqual("(14,32,50)",(A*x).__str__())
|
||||
self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n",(A*2).__str__())
|
||||
self.assertEqual("(14,32,50)",str(A*x))
|
||||
self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n",str(A*2))
|
||||
def test_changeComponent_matrix(self):
|
||||
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
||||
A.changeComponent(0,2,5)
|
||||
self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n",A.__str__())
|
||||
self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n",str(A))
|
||||
def test_component_matrix(self):
|
||||
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
||||
self.assertEqual(7,A.component(2,1),0.01)
|
||||
def test__add__matrix(self):
|
||||
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
||||
B = Matrix([[1,2,7],[2,4,5],[6,7,10]],3,3)
|
||||
self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n",(A+B).__str__())
|
||||
self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n",str(A+B))
|
||||
def test__sub__matrix(self):
|
||||
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
||||
B = Matrix([[1,2,7],[2,4,5],[6,7,10]],3,3)
|
||||
self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n",(A-B).__str__())
|
||||
self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n",str(A-B))
|
||||
def test_squareZeroMatrix(self):
|
||||
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|'
|
||||
+'\n|0,0,0,0,0|\n',squareZeroMatrix(5).__str__())
|
||||
+'\n|0,0,0,0,0|\n',str(squareZeroMatrix(5)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
unittest.main()
|
||||
|
|
Loading…
Reference in New Issue
Block a user