Challenge: Eigenvalue of matrix #2

Subdomeniu: Linear Algebra Foundations (linear-algebra-foundations)

Scor cont: 5.0 / 5

Submission status: Accepted

Submission score: 1.0

Submission ID: 464718444

Limbaj: python3

Link challenge: https://www.hackerrank.com/challenges/eigenvalue-of-matrix-2/problem

Cerinta

Find the eigenvalues of the matrix:
<img src="https://s3.amazonaws.com/hr-challenge-images/0/1445184257-2150ce1c5f-Screenshotfrom2015-10-18213408.png" title="Screenshot from 2015-10-18 21:34:08.png" />

Your answer should have the eigenvalues separated by a single line resembling this(with smaller value coming first):

<pre>
5
6
</pre>

Cod sursa

def determinant(A: list[list[int]]) -> int:
  return A[0][0]*A[1][1] - A[1][0]*A[0][1]

def matrixSubtract(B, A):
  C = [[0, 0], [0, 0]]
  for i in range(len(B)):
    for j in range(len(B[0])):
      C[i][j] = B[i][j] - A[i][j]
  return C

def scalarMultiply(A, k: int):
  Ak = [[0, 0], [0, 0]]
  for i in range(len(A)):
    for j in range(len(A[0])):
      Ak[i][j] = k*A[i][j]
  return Ak


if __name__ == "__main__":
  A = [[1, 2], [2, 4]]
  I2 = [[1, 0], [0, 1]] # 2 x 2 identity matrix

  eigval = -10
  lst_eigvals = []
  
  while (eigval < 10):
    val = determinant(matrixSubtract(scalarMultiply(I2, eigval), A))
    if (val == 0): # |lambdaI - A| = 0
      lst_eigvals += [eigval]
    eigval += 1
      
  print(*lst_eigvals, sep='\n')
HackerRank Linear Algebra Foundations – Eigenvalue of matrix #2