mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-21 08:42:03 +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
|
- constructor(components : list) : init the vector
|
||||||
- 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 / length 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
|
||||||
|
@ -31,12 +31,13 @@ This module contains some useful classes and functions for dealing with linear a
|
||||||
- computes the axpy operation
|
- computes the axpy operation
|
||||||
- function randomVector(N,a,b)
|
- function randomVector(N,a,b)
|
||||||
- returns a random vector of size N, with random integer components between 'a' and 'b'.
|
- returns a random vector of size N, with random integer components between 'a' and 'b'.
|
||||||
|
|
||||||
- class Matrix
|
- class Matrix
|
||||||
- This class represents a matrix of arbitrary size and operations on it.
|
- This class represents a matrix of arbitrary size and operations on it.
|
||||||
|
|
||||||
**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.
|
||||||
|
@ -45,6 +46,7 @@ This module contains some useful classes and functions for dealing with linear a
|
||||||
- height() : returns the height of the matrix
|
- height() : returns the height of the matrix
|
||||||
- operator + : implements the matrix-addition.
|
- operator + : implements the matrix-addition.
|
||||||
- operator - _ implements the matrix-subtraction
|
- operator - _ implements the matrix-subtraction
|
||||||
|
|
||||||
- function squareZeroMatrix(N)
|
- function squareZeroMatrix(N)
|
||||||
- returns a square zero-matrix of dimension NxN
|
- returns a square zero-matrix of dimension NxN
|
||||||
- function randomMatrix(W,H,a,b)
|
- function randomMatrix(W,H,a,b)
|
||||||
|
|
|
@ -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
|
||||||
|
@ -45,12 +45,12 @@ class Vector(object):
|
||||||
changeComponent(pos,value) : changes the specified component.
|
changeComponent(pos,value) : changes the specified component.
|
||||||
TODO: compare-operator
|
TODO: compare-operator
|
||||||
"""
|
"""
|
||||||
def __init__(self,components):
|
def __init__(self,components=[]):
|
||||||
"""
|
"""
|
||||||
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,52 +94,45 @@ 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 = []
|
if size == len(other):
|
||||||
if size == other.size():
|
result = [self.__components[i] + other.component(i) for i in range(size)]
|
||||||
for i in range(size):
|
return Vector(result)
|
||||||
result.append(self.__components[i] + other.component(i))
|
|
||||||
else:
|
else:
|
||||||
raise Exception("must have the same size")
|
raise Exception("must have the same size")
|
||||||
return Vector(result)
|
|
||||||
def __sub__(self,other):
|
def __sub__(self,other):
|
||||||
"""
|
"""
|
||||||
input: other vector
|
input: other vector
|
||||||
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 = []
|
if size == len(other):
|
||||||
if size == other.size():
|
result = [self.__components[i] - other.component(i) for i in range(size)]
|
||||||
for i in range(size):
|
return result
|
||||||
result.append(self.__components[i] - other.component(i))
|
|
||||||
else: # error case
|
else: # error case
|
||||||
raise Exception("must have the same size")
|
raise Exception("must have the same size")
|
||||||
return Vector(result)
|
|
||||||
def __mul__(self,other):
|
def __mul__(self,other):
|
||||||
"""
|
"""
|
||||||
mul implements the scalar multiplication
|
mul implements the scalar multiplication
|
||||||
and the dot-product
|
and the dot-product
|
||||||
"""
|
"""
|
||||||
ans = []
|
|
||||||
if isinstance(other,float) or isinstance(other,int):
|
if isinstance(other,float) or isinstance(other,int):
|
||||||
for c in self.__components:
|
ans = [c*other for c in self.__components]
|
||||||
ans.append(c*other)
|
return ans
|
||||||
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)
|
||||||
return summe
|
return summe
|
||||||
else: # error case
|
else: # error case
|
||||||
raise Exception("invalide operand!")
|
raise Exception("invalide operand!")
|
||||||
return Vector(ans)
|
|
||||||
def copy(self):
|
def copy(self):
|
||||||
"""
|
"""
|
||||||
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 +140,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 +149,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 +159,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 +183,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 +195,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 +259,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 +269,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 +307,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 +316,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)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -29,13 +29,13 @@ class Test(unittest.TestCase):
|
||||||
test for toString() method
|
test for toString() method
|
||||||
"""
|
"""
|
||||||
x = Vector([0,0,0,0,0,1])
|
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):
|
def test_size(self):
|
||||||
"""
|
"""
|
||||||
test for size()-method
|
test for size()-method
|
||||||
"""
|
"""
|
||||||
x = Vector([1,2,3,4])
|
x = Vector([1,2,3,4])
|
||||||
self.assertEqual(x.size(),4)
|
self.assertEqual(len(x),4)
|
||||||
def test_euclidLength(self):
|
def test_euclidLength(self):
|
||||||
"""
|
"""
|
||||||
test for the eulidean length
|
test for the eulidean length
|
||||||
|
@ -67,32 +67,32 @@ class Test(unittest.TestCase):
|
||||||
x = Vector([1,2,3])
|
x = Vector([1,2,3])
|
||||||
a = Vector([2,-1,4]) # for test of dot-product
|
a = Vector([2,-1,4]) # for test of dot-product
|
||||||
b = Vector([1,-2,-1])
|
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)
|
self.assertEqual((a*b),0)
|
||||||
def test_zeroVector(self):
|
def test_zeroVector(self):
|
||||||
"""
|
"""
|
||||||
test for the global function zeroVector(...)
|
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):
|
def test_unitBasisVector(self):
|
||||||
"""
|
"""
|
||||||
test for the global function unitBasisVector(...)
|
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):
|
def test_axpy(self):
|
||||||
"""
|
"""
|
||||||
test for the global function axpy(...) (operation)
|
test for the global function axpy(...) (operation)
|
||||||
"""
|
"""
|
||||||
x = Vector([1,2,3])
|
x = Vector([1,2,3])
|
||||||
y = Vector([1,0,1])
|
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):
|
def test_copy(self):
|
||||||
"""
|
"""
|
||||||
test for the copy()-method
|
test for the copy()-method
|
||||||
"""
|
"""
|
||||||
x = Vector([1,0,0,0,0,0])
|
x = Vector([1,0,0,0,0,0])
|
||||||
y = x.copy()
|
y = x.copy()
|
||||||
self.assertEqual(x.__str__(),y.__str__())
|
self.assertEqual(str(x),str(y))
|
||||||
def test_changeComponent(self):
|
def test_changeComponent(self):
|
||||||
"""
|
"""
|
||||||
test for the changeComponent(...)-method
|
test for the changeComponent(...)-method
|
||||||
|
@ -100,34 +100,34 @@ class Test(unittest.TestCase):
|
||||||
x = Vector([1,0,0])
|
x = Vector([1,0,0])
|
||||||
x.changeComponent(0,0)
|
x.changeComponent(0,0)
|
||||||
x.changeComponent(1,1)
|
x.changeComponent(1,1)
|
||||||
self.assertEqual(x.__str__(),"(0,1,0)")
|
self.assertEqual(str(x),"(0,1,0)")
|
||||||
def test_str_matrix(self):
|
def test_str_matrix(self):
|
||||||
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
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):
|
def test__mul__matrix(self):
|
||||||
A = Matrix([[1,2,3],[4,5,6],[7,8,9]],3,3)
|
A = Matrix([[1,2,3],[4,5,6],[7,8,9]],3,3)
|
||||||
x = Vector([1,2,3])
|
x = Vector([1,2,3])
|
||||||
self.assertEqual("(14,32,50)",(A*x).__str__())
|
self.assertEqual("(14,32,50)",str(A*x))
|
||||||
self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n",(A*2).__str__())
|
self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n",str(A*2))
|
||||||
def test_changeComponent_matrix(self):
|
def test_changeComponent_matrix(self):
|
||||||
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
||||||
A.changeComponent(0,2,5)
|
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):
|
def test_component_matrix(self):
|
||||||
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
||||||
self.assertEqual(7,A.component(2,1),0.01)
|
self.assertEqual(7,A.component(2,1),0.01)
|
||||||
def test__add__matrix(self):
|
def test__add__matrix(self):
|
||||||
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
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)
|
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):
|
def test__sub__matrix(self):
|
||||||
A = Matrix([[1,2,3],[2,4,5],[6,7,8]],3,3)
|
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)
|
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):
|
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|'
|
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__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|
Loading…
Reference in New Issue
Block a user