> Interview Breeze

Generating an identity matrix in Python

Problem

Write a function that generates an identity matrix. You may represent this data as a list of lists. The function will take a size parameter.

Solution

What is an identity matrix?

An identity matrix is an NxN matrix in which all the cells on the diagonal line between the upper left and bottom right are set to 1, and all other cells are 0. As an example, a 4x4 identity matrix would look like this:

[
    [1,0,0,0],
    [0,1,0,0],
    [0,0,1,0],
    [0,0,0,1]
]

The identity matrix plays a similar role with matrices that the number 1 plays with real numbers. For example, any matrix M that is multiplied with an identity matrix I will always return a matrix that is identical to the original M.

Implementing the function

We can implement a solution for this problem using either loops or list comprehensions. In both cases, we will have two counters, one tracking the current row we are at, and the other tracking the current column we are at. When the two counters are equal to one another, we set the cell to 1. In any other case, we set the cell to 0. To implement using a set of loops, our function would look like so:

def identity_matrix(size):
    result = []
    wi, hi = 0, 0
    while hi < size:
        wi = 0
        row = []
        while wi < size:
            row.append(1 if wi == hi else 0)
            wi += 1
        result.append(row)
        hi += 1
    return result

As a comprehension, we will do essentially the same thing as the function above, but in a more pythonic way:

def identity_matrix(size):
    return [[1 if hi == wi else 0 for wi in range(0,size)] for hi in range(0,size)]

You may also want to read:

Point of Descent

You are given an array that is comprised of positive integers. Initially, these numbers are ascending, but at some point they start descending. There are no duplicate integers in the array. Find the index of the maximum value.

Read More >>
Array Summing

Given an array containing N integers, write a class that contains two functions: and update function that will update a value at a given index, and a sum function that will sum all values between indexes I1 and I2.

Read More >>
Maximum profit by selling a stock

Write a function that takes an array of ticker prices for a given stock, and returns the maximum profit possible in that time frame.

Read More >>

Python Console