Home > OS >  Function is changing matrix
Function is changing matrix

Time:05-05

Just a warning that this is a college assignment, and therefore I am not allowed to use python functions other than len(). I don't mind if anyone wants to answer with functions or not, just know that's why my code looks terrible.

The assignment is for me to create a 10x10 matrix and with multiple functions add elements to it depending on the x or y position, checking if the space is available or not. The original instruction is to create a 10x10 with '.' instead of zeroes, so that it would look better in the terminal. I decided to keep using 0 and only change to '.' in the printing process. I print the matrix every time I make a change. I use this function:

def printMatrixF(M):
    fM = M
    for i in range(10):
        for j in range(10):
            if fM[i][j] == 0:
                fM[i][j] = '.'
            print(fM[i][j],end=" ")
        print()

But this function is somehow changing the M value, even though I'm pretty sure it shouldn't. Here is a smaller portion of the code that shows my exact problem:

def createMatrix():
    a = [0]*10
    for i in range(10):
        a[i] = [0]*10
    return a

def printMatrix(M):
    for i in range(len(M)):
        print(M[i])

def printMatrixF(M):
    fM = M
    for i in range(10):
        for j in range(10):
            if fM[i][j] == 0:
                fM[i][j] = '.'
            print(fM[i][j],end=" ")
        print()

M = createMatrix()
printMatrix(M)
printMatrixF(M)
printMatrix(M)

The printMatrix() function only prints the matrix, and the printMatrixF() has the added change from 0 to '.' in it. This feels so dumb but I have no idea what's causing this.

(Edit: I'm using the same function but using if to revert back the '.'s to 0s (and it works I guess).

CodePudding user response:

The problem is that fM = M only assigns another name to object M refers to — so you need to make a copy of it. This could be done using the copy module, but since you can't use that, you can do it manually by making use of the copy() method that all list objects have.

In the code below I've created a copyMatrix(M) function to illustrate how to use it:

def createMatrix():
    a = [0]*10
    for i in range(10):
        a[i] = [0]*10
    return a

def printMatrix(M):
    for i in range(len(M)):
        print(M[i])

def copyMatrix(M):
    """Return a copy of matrix M."""
    mcopy = []
    for i in range(len(M)):
        # Append copy of sublist.
        mcopy.append(M[i].copy())  # Could also use M[i][:]
    return mcopy

def printMatrixF(M):
    fM = copyMatrix(M)
    for i in range(10):
        for j in range(10):
            if fM[i][j] == 0:
                fM[i][j] = '.'
            print(fM[i][j],end=" ")
        print()

M = createMatrix()
printMatrix(M)
print()
printMatrixF(M)
print()
printMatrix(M)

  • Related