Converting a 1D Array of Strings to a 2D Array in Python

Posted on

Problem

I was solving this question on a site that gives you a 1d array called grid

grid = ['top left',    'top middle',    'top right',
        'middle left', 'center',        'middle right',
        'bottom left', 'bottom middle', 'bottom right']

and you’re expected to write a method fire(x,y) that takes in two coordinates and gives you back where you hit the grid.

For example:

fire(0,0) # 'top left'
fire(1,2) # 'bottom middle'

Here is my solution, I used NumPy for it.

import numpy as np
def fire(x,y):
#the grid is preloaded as you can see in description

    oneDArray = np.array(grid)
    twoDArray = oneDArray.reshape(3,3)

    return twoDArray[y][x]

I’m looking to get some feedback on the answer.

Solution

That works, but if your only goal is to implement fire(x, y), then NumPy is overkill.

def fire(x, y):
    return grid[3 * y + x]

A few issues:

  1. Probably better to follow pep8
  2. This isn’t a method, it is a function
  3. When doing 2D numpy indexes, you can do twoDArray[x, y]
  4. You don’t really need a numpy array, a list of lists works just as well. Or better yet just just translate the 2D index into a linear index mathematically. This also avoids the substantial overhead of converting the list to a numpy array. You could even use np.ravel_multi_index to do the 2D to 1D conversion for you.

Leave a Reply

Your email address will not be published. Required fields are marked *