Click4Ai

26.

Easy

Write a function identity_matrix(n) that creates an n×n identity matrix without using np.eye() or np.identity(). An identity matrix has 1s on the main diagonal and 0s elsewhere.

Example:

Input: n = 3

Output: [[1, 0, 0],

[0, 1, 0],

[0, 0, 1]]

Constraints:

  • 1 <= n <= 100
  • Return a list of lists
  • Test Cases

    Test Case 1
    Input: 3
    Expected: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    Test Case 2
    Input: 2
    Expected: [[1, 0], [0, 1]]
    Test Case 3
    Input: 1
    Expected: [[1]]
    + 2 hidden test cases