mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-07-05 01:09:40 +08:00
psf/black code formatting (#1277)
This commit is contained in:

committed by
Christian Clauss

parent
07f04a2e55
commit
9eac17a408
@ -311,8 +311,10 @@ class Matrix:
|
||||
return Matrix([[element * other for element in row] for row in self.rows])
|
||||
elif isinstance(other, Matrix):
|
||||
if self.num_columns != other.num_rows:
|
||||
raise ValueError("The number of columns in the first matrix must "
|
||||
"be equal to the number of rows in the second")
|
||||
raise ValueError(
|
||||
"The number of columns in the first matrix must "
|
||||
"be equal to the number of rows in the second"
|
||||
)
|
||||
return Matrix(
|
||||
[
|
||||
[Matrix.dot_product(row, column) for column in other.columns()]
|
||||
@ -320,7 +322,9 @@ class Matrix:
|
||||
]
|
||||
)
|
||||
else:
|
||||
raise TypeError("A Matrix can only be multiplied by an int, float, or another matrix")
|
||||
raise TypeError(
|
||||
"A Matrix can only be multiplied by an int, float, or another matrix"
|
||||
)
|
||||
|
||||
def __pow__(self, other):
|
||||
if not isinstance(other, int):
|
||||
|
@ -39,8 +39,10 @@ def multiply(matrix_a, matrix_b):
|
||||
rows, cols = _verify_matrix_sizes(matrix_a, matrix_b)
|
||||
|
||||
if cols[0] != rows[1]:
|
||||
raise ValueError(f'Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) '
|
||||
f'and ({rows[1]},{cols[1]})')
|
||||
raise ValueError(
|
||||
f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) "
|
||||
f"and ({rows[1]},{cols[1]})"
|
||||
)
|
||||
for i in range(rows[0]):
|
||||
list_1 = []
|
||||
for j in range(cols[1]):
|
||||
@ -59,7 +61,7 @@ def identity(n):
|
||||
:return: Identity matrix of shape [n, n]
|
||||
"""
|
||||
n = int(n)
|
||||
return [[int(row == column) for column in range(n)] for row in range(n)]
|
||||
return [[int(row == column) for column in range(n)] for row in range(n)]
|
||||
|
||||
|
||||
def transpose(matrix, return_map=True):
|
||||
@ -75,15 +77,15 @@ def transpose(matrix, return_map=True):
|
||||
|
||||
|
||||
def minor(matrix, row, column):
|
||||
minor = matrix[:row] + matrix[row + 1:]
|
||||
minor = [row[:column] + row[column + 1:] for row in minor]
|
||||
minor = matrix[:row] + matrix[row + 1 :]
|
||||
minor = [row[:column] + row[column + 1 :] for row in minor]
|
||||
return minor
|
||||
|
||||
|
||||
def determinant(matrix):
|
||||
if len(matrix) == 1:
|
||||
return matrix[0][0]
|
||||
|
||||
|
||||
res = 0
|
||||
for x in range(len(matrix)):
|
||||
res += matrix[0][x] * determinant(minor(matrix, 0, x)) * (-1) ** x
|
||||
@ -99,10 +101,13 @@ def inverse(matrix):
|
||||
for i in range(len(matrix)):
|
||||
for j in range(len(matrix)):
|
||||
matrix_minor[i].append(determinant(minor(matrix, i, j)))
|
||||
|
||||
cofactors = [[x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])] for row in range(len(matrix))]
|
||||
|
||||
cofactors = [
|
||||
[x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])]
|
||||
for row in range(len(matrix))
|
||||
]
|
||||
adjugate = transpose(cofactors)
|
||||
return scalar_multiply(adjugate, 1/det)
|
||||
return scalar_multiply(adjugate, 1 / det)
|
||||
|
||||
|
||||
def _check_not_integer(matrix):
|
||||
@ -122,8 +127,10 @@ def _verify_matrix_sizes(matrix_a, matrix_b):
|
||||
shape = _shape(matrix_a)
|
||||
shape += _shape(matrix_b)
|
||||
if shape[0] != shape[2] or shape[1] != shape[3]:
|
||||
raise ValueError(f"operands could not be broadcast together with shape "
|
||||
f"({shape[0], shape[1]}), ({shape[2], shape[3]})")
|
||||
raise ValueError(
|
||||
f"operands could not be broadcast together with shape "
|
||||
f"({shape[0], shape[1]}), ({shape[2], shape[3]})"
|
||||
)
|
||||
return [shape[0], shape[2]], [shape[1], shape[3]]
|
||||
|
||||
|
||||
@ -132,13 +139,19 @@ def main():
|
||||
matrix_b = [[3, 4], [7, 4]]
|
||||
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
|
||||
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
|
||||
print('Add Operation, %s + %s = %s \n' %(matrix_a, matrix_b, (add(matrix_a, matrix_b))))
|
||||
print('Multiply Operation, %s * %s = %s \n' %(matrix_a, matrix_b, multiply(matrix_a, matrix_b)))
|
||||
print('Identity: %s \n' %identity(5))
|
||||
print('Minor of %s = %s \n' %(matrix_c, minor(matrix_c, 1, 2)))
|
||||
print('Determinant of %s = %s \n' %(matrix_b, determinant(matrix_b)))
|
||||
print('Inverse of %s = %s\n'%(matrix_d, inverse(matrix_d)))
|
||||
print(
|
||||
"Add Operation, %s + %s = %s \n"
|
||||
% (matrix_a, matrix_b, (add(matrix_a, matrix_b)))
|
||||
)
|
||||
print(
|
||||
"Multiply Operation, %s * %s = %s \n"
|
||||
% (matrix_a, matrix_b, multiply(matrix_a, matrix_b))
|
||||
)
|
||||
print("Identity: %s \n" % identity(5))
|
||||
print("Minor of %s = %s \n" % (matrix_c, minor(matrix_c, 1, 2)))
|
||||
print("Determinant of %s = %s \n" % (matrix_b, determinant(matrix_b)))
|
||||
print("Inverse of %s = %s\n" % (matrix_d, inverse(matrix_d)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
@ -13,6 +13,8 @@ Converting to matrix,
|
||||
So we just need the n times multiplication of the matrix [1,1],[1,0]].
|
||||
We can decrease the n times multiplication by following the divide and conquer approach.
|
||||
"""
|
||||
|
||||
|
||||
def multiply(matrix_a, matrix_b):
|
||||
matrix_c = []
|
||||
n = len(matrix_a)
|
||||
|
@ -2,26 +2,21 @@ def search_in_a_sorted_matrix(mat, m, n, key):
|
||||
i, j = m - 1, 0
|
||||
while i >= 0 and j < n:
|
||||
if key == mat[i][j]:
|
||||
print('Key %s found at row- %s column- %s' % (key, i + 1, j + 1))
|
||||
print("Key %s found at row- %s column- %s" % (key, i + 1, j + 1))
|
||||
return
|
||||
if key < mat[i][j]:
|
||||
i -= 1
|
||||
else:
|
||||
j += 1
|
||||
print('Key %s not found' % (key))
|
||||
print("Key %s not found" % (key))
|
||||
|
||||
|
||||
def main():
|
||||
mat = [
|
||||
[2, 5, 7],
|
||||
[4, 8, 13],
|
||||
[9, 11, 15],
|
||||
[12, 17, 20]
|
||||
]
|
||||
mat = [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]]
|
||||
x = int(input("Enter the element to be searched:"))
|
||||
print(mat)
|
||||
search_in_a_sorted_matrix(mat, len(mat), len(mat[0]), x)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
@ -28,7 +28,7 @@ class Matrix:
|
||||
|
||||
# Prefix
|
||||
s = "Matrix consist of %d rows and %d columns\n" % (self.row, self.column)
|
||||
|
||||
|
||||
# Make string identifier
|
||||
max_element_length = 0
|
||||
for row_vector in self.array:
|
||||
@ -37,16 +37,18 @@ class Matrix:
|
||||
string_format_identifier = "%%%ds" % (max_element_length,)
|
||||
|
||||
# Make string and return
|
||||
def single_line(row_vector):
|
||||
def single_line(row_vector):
|
||||
nonlocal string_format_identifier
|
||||
line = "["
|
||||
line += ", ".join(string_format_identifier % (obj,) for obj in row_vector)
|
||||
line += "]"
|
||||
return line
|
||||
|
||||
s += "\n".join(single_line(row_vector) for row_vector in self.array)
|
||||
return s
|
||||
|
||||
def __repr__(self): return str(self)
|
||||
def __repr__(self):
|
||||
return str(self)
|
||||
|
||||
def validateIndices(self, loc: tuple):
|
||||
"""
|
||||
@ -60,9 +62,12 @@ class Matrix:
|
||||
>>> a.validateIndices((0, 0))
|
||||
True
|
||||
"""
|
||||
if not(isinstance(loc, (list, tuple)) and len(loc) == 2): return False
|
||||
elif not(0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False
|
||||
else: return True
|
||||
if not (isinstance(loc, (list, tuple)) and len(loc) == 2):
|
||||
return False
|
||||
elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column):
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
def __getitem__(self, loc: tuple):
|
||||
"""
|
||||
@ -115,7 +120,7 @@ class Matrix:
|
||||
result = Matrix(self.row, self.column)
|
||||
for r in range(self.row):
|
||||
for c in range(self.column):
|
||||
result[r,c] = self[r,c] + another[r,c]
|
||||
result[r, c] = self[r, c] + another[r, c]
|
||||
return result
|
||||
|
||||
def __neg__(self):
|
||||
@ -135,10 +140,11 @@ class Matrix:
|
||||
result = Matrix(self.row, self.column)
|
||||
for r in range(self.row):
|
||||
for c in range(self.column):
|
||||
result[r,c] = -self[r,c]
|
||||
result[r, c] = -self[r, c]
|
||||
return result
|
||||
|
||||
def __sub__(self, another): return self + (-another)
|
||||
def __sub__(self, another):
|
||||
return self + (-another)
|
||||
|
||||
def __mul__(self, another):
|
||||
"""
|
||||
@ -154,21 +160,24 @@ class Matrix:
|
||||
[-2, -2, -6]
|
||||
"""
|
||||
|
||||
if isinstance(another, (int, float)): # Scalar multiplication
|
||||
if isinstance(another, (int, float)): # Scalar multiplication
|
||||
result = Matrix(self.row, self.column)
|
||||
for r in range(self.row):
|
||||
for c in range(self.column):
|
||||
result[r,c] = self[r,c] * another
|
||||
result[r, c] = self[r, c] * another
|
||||
return result
|
||||
elif isinstance(another, Matrix): # Matrix multiplication
|
||||
assert(self.column == another.row)
|
||||
elif isinstance(another, Matrix): # Matrix multiplication
|
||||
assert self.column == another.row
|
||||
result = Matrix(self.row, another.column)
|
||||
for r in range(self.row):
|
||||
for c in range(another.column):
|
||||
for i in range(self.column):
|
||||
result[r,c] += self[r,i] * another[i,c]
|
||||
result[r, c] += self[r, i] * another[i, c]
|
||||
return result
|
||||
else: raise TypeError("Unsupported type given for another (%s)" % (type(another),))
|
||||
else:
|
||||
raise TypeError(
|
||||
"Unsupported type given for another (%s)" % (type(another),)
|
||||
)
|
||||
|
||||
def transpose(self):
|
||||
"""
|
||||
@ -191,7 +200,7 @@ class Matrix:
|
||||
result = Matrix(self.column, self.row)
|
||||
for r in range(self.row):
|
||||
for c in range(self.column):
|
||||
result[c,r] = self[r,c]
|
||||
result[c, r] = self[r, c]
|
||||
return result
|
||||
|
||||
def ShermanMorrison(self, u, v):
|
||||
@ -220,28 +229,31 @@ class Matrix:
|
||||
|
||||
# Size validation
|
||||
assert isinstance(u, Matrix) and isinstance(v, Matrix)
|
||||
assert self.row == self.column == u.row == v.row # u, v should be column vector
|
||||
assert u.column == v.column == 1 # u, v should be column vector
|
||||
assert self.row == self.column == u.row == v.row # u, v should be column vector
|
||||
assert u.column == v.column == 1 # u, v should be column vector
|
||||
|
||||
# Calculate
|
||||
vT = v.transpose()
|
||||
numerator_factor = (vT * self * u)[0, 0] + 1
|
||||
if numerator_factor == 0: return None # It's not invertable
|
||||
if numerator_factor == 0:
|
||||
return None # It's not invertable
|
||||
return self - ((self * u) * (vT * self) * (1.0 / numerator_factor))
|
||||
|
||||
|
||||
# Testing
|
||||
if __name__ == "__main__":
|
||||
|
||||
def test1():
|
||||
# a^(-1)
|
||||
ainv = Matrix(3, 3, 0)
|
||||
for i in range(3): ainv[i,i] = 1
|
||||
for i in range(3):
|
||||
ainv[i, i] = 1
|
||||
print("a^(-1) is %s" % (ainv,))
|
||||
# u, v
|
||||
u = Matrix(3, 1, 0)
|
||||
u[0,0], u[1,0], u[2,0] = 1, 2, -3
|
||||
u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3
|
||||
v = Matrix(3, 1, 0)
|
||||
v[0,0], v[1,0], v[2,0] = 4, -2, 5
|
||||
v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5
|
||||
print("u is %s" % (u,))
|
||||
print("v is %s" % (v,))
|
||||
print("uv^T is %s" % (u * v.transpose()))
|
||||
@ -250,6 +262,7 @@ if __name__ == "__main__":
|
||||
|
||||
def test2():
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
||||
test2()
|
||||
test2()
|
||||
|
@ -6,6 +6,8 @@ This problem has been solved through recursive way.
|
||||
i) matrix should be only one or two dimensional
|
||||
ii)column of all the row should be equal
|
||||
"""
|
||||
|
||||
|
||||
def checkMatrix(a):
|
||||
# must be
|
||||
if type(a) == list and len(a) > 0:
|
||||
@ -51,7 +53,7 @@ def spiralPrint(a):
|
||||
# vertical printing up
|
||||
for i in range(matRow - 2, 0, -1):
|
||||
print(a[i][0]),
|
||||
remainMat = [row[1:matCol - 1] for row in a[1:matRow - 1]]
|
||||
remainMat = [row[1 : matCol - 1] for row in a[1 : matRow - 1]]
|
||||
if len(remainMat) > 0:
|
||||
spiralPrint(remainMat)
|
||||
else:
|
||||
@ -62,5 +64,5 @@ def spiralPrint(a):
|
||||
|
||||
|
||||
# driver code
|
||||
a = [[1 , 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]
|
||||
a = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
|
||||
spiralPrint(a)
|
||||
|
@ -29,8 +29,9 @@ logger.addHandler(stream_handler)
|
||||
|
||||
|
||||
@pytest.mark.mat_ops
|
||||
@pytest.mark.parametrize(('mat1', 'mat2'), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e),
|
||||
(mat_f, mat_h)])
|
||||
@pytest.mark.parametrize(
|
||||
("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]
|
||||
)
|
||||
def test_addition(mat1, mat2):
|
||||
if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2):
|
||||
with pytest.raises(TypeError):
|
||||
@ -48,8 +49,9 @@ def test_addition(mat1, mat2):
|
||||
|
||||
|
||||
@pytest.mark.mat_ops
|
||||
@pytest.mark.parametrize(('mat1', 'mat2'), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e),
|
||||
(mat_f, mat_h)])
|
||||
@pytest.mark.parametrize(
|
||||
("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]
|
||||
)
|
||||
def test_subtraction(mat1, mat2):
|
||||
if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2):
|
||||
with pytest.raises(TypeError):
|
||||
@ -67,8 +69,9 @@ def test_subtraction(mat1, mat2):
|
||||
|
||||
|
||||
@pytest.mark.mat_ops
|
||||
@pytest.mark.parametrize(('mat1', 'mat2'), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e),
|
||||
(mat_f, mat_h)])
|
||||
@pytest.mark.parametrize(
|
||||
("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)]
|
||||
)
|
||||
def test_multiplication(mat1, mat2):
|
||||
if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2):
|
||||
logger.info(f"\n\t{test_multiplication.__name__} returned integer")
|
||||
@ -81,7 +84,9 @@ def test_multiplication(mat1, mat2):
|
||||
assert theo == act
|
||||
else:
|
||||
with pytest.raises(ValueError):
|
||||
logger.info(f"\n\t{test_multiplication.__name__} does not meet dim requirements")
|
||||
logger.info(
|
||||
f"\n\t{test_multiplication.__name__} does not meet dim requirements"
|
||||
)
|
||||
assert matop.subtract(mat1, mat2)
|
||||
|
||||
|
||||
@ -100,7 +105,7 @@ def test_identity():
|
||||
|
||||
|
||||
@pytest.mark.mat_ops
|
||||
@pytest.mark.parametrize('mat', [mat_a, mat_b, mat_c, mat_d, mat_e, mat_f])
|
||||
@pytest.mark.parametrize("mat", [mat_a, mat_b, mat_c, mat_d, mat_e, mat_f])
|
||||
def test_transpose(mat):
|
||||
if (np.array(mat)).shape < (2, 2):
|
||||
with pytest.raises(TypeError):
|
||||
|
Reference in New Issue
Block a user