0

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]]
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
  • 1
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Yevhen Kuzmovych Nov 14 '22 at 21:21

3 Answers3

0

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?

Raboro
  • 76
  • 3
0

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.]])
vighub
  • 173
  • 1
  • 6
0

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) ]
user19077881
  • 3,643
  • 2
  • 3
  • 14
  • I hate to ask silly questions but what is the difference between this and the multiplication method i used. – ilyas Abdulkadir Nov 26 '22 at 17:04
  • When you use `[-1] * n` then you are creating multiple references to the same thing. So changing one of them will change all of them. You can explore this using id() to show the addresses. Using a List comprehension avoids such multi-referencing because it creates separate objects and gives each a value of -1. Hope this helps. – user19077881 Nov 26 '22 at 17:18