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 do I replace the entries in a matrix?

row_len = 5
col_len = 5

matrix = []

#Fills the matrix with #'s
def fill_maze():
    row = []
    for i in range(row_len):
        row.append("#")
    for i in range (col_len):
        matrix.append(row)

# Draws the maze to the screen
def draw():
    for i in range(col_len):
        row = matrix[i]
        a = ("")
        for i in row:
            a += i
        print(a)

#Swaps out the character in the given coordinate with @
def dig(x, y):
    row = matrix[y]
    row[x] = "@"
    matrix[y] = row

fill_maze()
dig(2, 3)
print("")
draw()

I’m making this text maze game where the character has to traverse a maze and I have the maze stored as a matrix. Currently I’m facing trouble changing out parts of the maze using this dig(x, y) function.

I think I’ve pinned down the problem to this function:

def dig(x, y):
    row = matrix[y]
    row[x] = "@"
    matrix[y] = row

When I run the program I expect it to output:

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

#####
#####
#####
##@##
#####

But instead it outputs:

##@##
##@##
##@##
##@##
##@##

I tried removing this part of the function: matrix[y] = row

I also tried:

def dig(x, y):
    matrix[x][y] = "@"

but that gave the same output.

>Solution :

The issue isn’t with how you try to update the matrix, but how you initialize it – you have the same row multiple times, so when you think you’re updating one of them, you’re actually updating "all" of them, because they’re actually the same row variable.
instead, you should use a different row array for each row:

#Fills the matrix with #'s
def fill_maze():
    for i in range (col_len):
        row = []
        for i in range(row_len):
            row.append("#")

        matrix.append(row)

Or, in more idiomatic fashion:

def fill_maze():
    matrix = [['#' * col_len] for _ in range(row_len)]
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