Skip to content
DeepForgeby svx
All problems
EasyLinear Algebrala-064

Inverse of Diagonal Matrix

Problem

Return the inverse of a square diagonal matrix: reciprocals on the diagonal and zeros elsewhere.

If any diagonal entry is 0, the matrix is singular; return None.

Hint

Invert each nonzero diagonal entry; off-diagonal entries stay 0.

Test cases

case 1
in: [[[2,0],[0,4]]]
expected: [[0.5,0],[0,0.25]]
case 2
in: [[[1,0,0],[0,2,0],[0,0,5]]]
expected: [[1,0,0],[0,0.5,0],[0,0,0.2]]
case 3
in: [[[1,0],[0,1]]]
expected: [[1,0],[0,1]]
case 4
in: [[[0,0],[0,2]]]
expected: null
Starter codePython
def inverse_diagonal(A):
    # Your code here
    pass

4 test cases · run your code against them in the editor