Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

def itera_mundo(mundo):

    colunas = len(mundo[0])
    linhas = len(mundo)
    ncolunas = colunas + 2
    nlinhas = linhas + 2
    novo_mundo=cria_mundo(nlinhas,ncolunas)
    for linha in range(linhas):
        for coluna in range(colunas):
            if mundo[linha][coluna] == 1:
                novo_mundo[linha+1][coluna+1] = 1
    return novo_mundo

def cria_mundo(linhas, colunas):

    mini_matriz = []
    matriz = []
    for x in range(colunas):
        mini_matriz.append(0)
    for z in range(linhas):
        matriz.append(mini_matriz)
    return matriz

print(itera_mundo([[1,0],[0,0]]))

cria_mundo creates a matrix made out of 0s where linhas is the amount of lines and colunas is the amount of columns in the matrix. Each line consists of colunas elements, so basically if linhas = 2 and colunas = 3 it'd return a list like [[0,0,0], [0,0,0]].

Now, I want to use itera_mundo, where mundo is also a matrix in a list. This function takes cria_mundo and adds 2 columns and 2 lines to the mundo matrix, one on each side, basically encasing the mundo matrix in a box of 0s. That is how it's supposed to work, but it doesn't, because if mundo was [[1,0], [0,1]] it'd output [[0,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,0]] but instead it outputs [[0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0]] for some odd reason.

How could I fix this without imports, breaks or continues?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
160 views
Welcome To Ask or Share your Answers For Others

1 Answer

    def itera_mundo(mundo):

        colunas = len(mundo[0])
        linhas = len(mundo)
        ncolunas = colunas + 2
        nlinhas = linhas + 2
        novo_mundo=cria_mundo(nlinhas,ncolunas)
        for linha in range(linhas):
            for coluna in range(colunas):
                if mundo[linha][coluna] == 1:
                    novo_mundo[linha+1][coluna+1] = 1
        return novo_mundo

    def cria_mundo(linhas, colunas):

        mini_matriz = []
        matriz = []
        for x in range(colunas):
            mini_matriz.append(0)
        for z in range(linhas):
            matriz.append(mini_matriz[:])
        return matriz

    print(itera_mundo([[1,0],[0,0]]))

output:

    >python mundo.py
    [[0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...