Soluție HackerRank pentru Linear Algebra Foundations #7 - The 1000th Power of a Matrix, subdomeniul Linear Algebra Foundations, în Python 3. Include…
- Problemă: Linear Algebra Foundations #7 - The 1000th Power of a Matrix
- Domeniu: Linear Algebra Foundations
- Limbaj: Python 3
Challenge: Linear Algebra Foundations #7 – The 1000th Power of a Matrix
Subdomeniu: Linear Algebra Foundations (linear-algebra-foundations)
Scor cont: 5.0 / 5
Submission status: Accepted
Submission score: 1.0
Submission ID: 464718836
Limbaj: python3
Link challenge: https://www.hackerrank.com/challenges/linear-algebra-foundations-7-the-1000th-power-of-a-matrix/problem
Cerință
You are provided a matrix A =
[-2 -9 ]
[ 1 4 ]
The 1000<sup>th</sup> power of A, i.e. A<sup>1000</sup> =
[A B]
[C D]
In the text box below, enter the integers A, B, C and D each on a new line, respectively. Do not leave any leading or trailing spaces.
Cod sursă
def matrix_mul(A, B):
ROWS_A, COLS_A = len(A), len(A[0])
ROWS_B, COLS_B = len(B), len(B[0])
assert COLS_A == ROWS_B
COMMON_D = ROWS_B
# zeros for Rows-A x Cols-B
M_TIMES = []
for r in range(ROWS_A):
M_TIMES.append( [0] * COLS_B )
# Loop over Rows-A, then Cols-B, then the common dimension
for rA in range(ROWS_A):
for cB in range(COLS_B):
for t in range(COMMON_D):
M_TIMES[rA][cB] += A[rA][t]*B[t][cB]
return M_TIMES
def print_matrix(M, skip_indexes=[]):
ROWS, COLS = len(M), len(M[0])
for r in range(ROWS):
for c in range(COLS):
if skip_indexes and skip_indexes[r][c]:
continue
print(M[r][c])
#####
A = [[-2,-9],[1,4]]
B = A
EXP=1000
for _ in range(EXP-1):
B = matrix_mul(B, A)
# print(B)
print_matrix(B)
