Home > Blockchain >  How to replace single item in a 2D array? double indexing not working
How to replace single item in a 2D array? double indexing not working

Time:11-15

I have tried to use double indexing but this has not worked for me.

P.S check my work below

As you can see my code is not replacing only the digit at x,y position but every position at x.

Example variables for solution

field =[[0, 1, 1],[1, 0, 1],[0, 0, 1]]
x_axis = 1
y_axis = 1

Input

def solution(field, x, y):
    arr = [[-1] * len(field)]*len(field)
    print(arr)
    total_mines = 0
    for array in field:
        temp_mines = array[x-1]   array[x]   array[x 1]
        total_mines  = temp_mines
    arr[y][x]) = int(total_mines)
    print(arr)

Output

[[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
[[-1, 5, -1], [-1, 5, -1], [-1, 5, -1]]

CodePudding user response:

Why can´t you just replace your item like this:

def solution(field, x, y):
   field[x][y] = 5 # insert any number you want

Why are you iterating over your 2D array?

CodePudding user response:

For this you can use also numpy, that has not the reference problem stated by Yevhen Kuzmovych

import numpy as np

def solution(field, x, y):
  arr =  -1*np.ones((len(field), len(field))) # numpy matrix
  total_mines = 0
  for array in field:
    temp_mines = array[x-1]   array[x]   array[x 1]
    total_mines  = temp_mines
  arr[y][x]) = int(total_mines)
  # or arr[y,x] = int(total_mines)
  print(arr)

Output:

array([[-1., -1., -1.],
      [-1.,  5., -1.],
      [-1., -1., -1.]])

CodePudding user response:

You can simply create your array using a list comprehension which will avoid the multi-reference issue already mentioned and your code will then work as you want.

sizef = len(field)
arr = [ [-1 for a in range(sizef)] for b in range(sizef) ]
  • Related