Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i change position of value in numpy array?

how can i change position of green circle by coordinates(x, y) in numpy array?

import numpy as np
matrix = np.array(
    [
        ['🟢', '⬛', '⬛', '⬛'],
        ['⬛', '⬛', '⬛', '⬛'],
        ['⬛', '⬛', '⬛', '⬛'],
        ['⬛', '⬛', '⬛', '⬛']
    ]
)

x, y = tuple(zip(*np.where(matrix=='🟢')))[0]
yield "\n".join("".join(x for x in i) for i in matrix)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can set the old position to square and the new to circle:

old_pos = (0,0)
new_pos = (1,2)

def change_pos(matrix,old,new):
    matrix[old] = '⬛'
    matrix[new] = '🟢'
change_pos(matrix, old_pos, new_pos)
matrix

output:

array([['⬛', '⬛', '⬛', '⬛'],
       ['⬛', '⬛', '🟢', '⬛'],
       ['⬛', '⬛', '⬛', '⬛'],
       ['⬛', '⬛', '⬛', '⬛']], dtype='<U1')

using a class

If your goal is to make some kind of game, you should use a class for your board:

import numpy as np
class Matrix():
    def __init__(self, pos=(0,0), size=(3,3)):
        self.pos = pos
        self.matrix = np.empty(size, dtype='<U1')
        self.matrix[:,:] = '⬛'
        self.matrix[pos] = '🟢'
    
    def __repr__(self):
        return self.matrix.__repr__()
    
    def __str__(self):
        return self.matrix.__str__()
    
    def change_pos(self, new):
        self.matrix[self.pos] = '⬛'
        self.matrix[new] = '🟢'
        self.pos = new

example:

m = Matrix()
print(m)

m.change_pos((2,1))
print(m)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading