I'm working through a tutorial on GeekforGeeks website and noticed that they are checking a point in an array using board[x,y]
, which I've never seen before. I don't think this would work, but when I run the program, everything goes as expected.
I tried running a smaller code example using their method outlined above vs the method I'm more familiar with (board[x][y]
), but when I run my code, I get TypeError: list indices must be integers or slices, not tuple
My code:
board = [[1,1,1], [1,2,2], [1,2,2]] win = 'True' if board[1][1] == 2: win = 'True by normal standards' print(win) if board[1, 1] == 2: win = 'True by weird standards' print(win) print(win)
Their code:
def row_win(board, player): for x in range(len(board)): win = True for y in range(len(board)): if board[x, y] != player: win = False continue if win == True: return(win) return(win)
Can someone explain to me why board[x,y]
works, and what exactly is happening? I've never seen this before except to create lists, and am not grasping it conceptually.
So here we find that both codes are almost similar but still there are difference in the outputs. So the reason behind this is that for many types of objects, x += y will modify the object referred to by x in-place, whereas x = x + y will create a new object and reassign x to it.
board is the name of the function's parameter. theBoard is a variable whose value is used as the argument that initializes the parameter when you call printBoard .
It means that the function you have called returns an iterable, and the index 0 of the iterable is assigned to x and the index 1 is assigned to y.
With x = x + 1 , the interpreter will treat it like x = x. __add__(1) , while x += 1 will be x = x. __iadd(1) , which can be much more efficient because it doesn't necessarily need to make a copy of x . x += 1 actually becomes x = x.
They're able to do that since they're using NumPy, which won't throw an error on that.
>>> a = np.array([[1,1,1], [1,2,2], [1,2,2]]) >>> a[1,1] 2 >>> # equivalent to >>> a = [[1,1,1], [1,2,2], [1,2,2]] >>> a[1][1] 2 >>>
That works because the object they are using (in this case numpy array) overloads the __getitem__
method. See this toy example:
class MyArray: def __init__(self, arr): self.arr = arr def __getitem__(self, t): return self.arr[t[0]][t[1]] myarr = MyArray([[1,1,1], [1,2,2], [1,2,2]]) print(myarr[0,1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With