Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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]
share|improve this answer
    
very nice solution. I love it. –  HussienK Jun 23 at 21:11

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.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.