pythonmatrixcube

Variable Updating (Python)


I am trying to create a 3D cube matrix and here is the matrix:

cube = [
    [
        ['W', 'W', 'W'],
        ['W', 'W', 'W'],
        ['W', 'W', 'W']
    ],   
    [
        ['G', 'G', 'G'],
        ['G', 'G', 'G'],
        ['G', 'G', 'G']
    ],
    [
        ['R', 'R', 'R'],
        ['R', 'R', 'R'],
        ['R', 'R', 'R']
    ],
    [
        ['B', 'B', 'B'],
        ['B', 'B', 'B'],
        ['B', 'B', 'B']
    ],
    [
        ['O', 'O', 'O'],
        ['O', 'O', 'O'],
        ['O', 'O', 'O']
    ],
    [
        ['Y', 'Y', 'Y'],
        ['Y', 'Y', 'Y'],
        ['Y', 'Y', 'Y']
    ],
]

I also have a function with the rotations:

def cube_rotation(rotation):
    if 'U' in rotation:
        cube_g = cube[1]
        direction = 1
        if '\'' in rotation: direction = -1;
        for i in range(1,4):
            cube[i][0] = cube[i+direction][0];
        cube[4][0] = cube_g[0];
    print(cube)
cube_rotation('U')

The U rotation basically means to turn the top of the cube to left. [![[![enter image description here][1]][1] [1]: https://i.sstatic.net/XYqVm.png

What I expect as the outcome is:

[
[['W', 'W', 'W'], ['W', 'W', 'W'], ['W', 'W', 'W']], 
[['R', 'R', 'R'], ['G', 'G', 'G'], ['G', 'G', 'G']], 
[['B', 'B', 'B'], ['R', 'R', 'R'], ['R', 'R', 'R']], 
[['O', 'O', 'O'], ['B', 'B', 'B'], ['B', 'B', 'B']], 
[['G', 'G', 'G'], ['O', 'O', 'O'], ['O', 'O', 'O']], # Point of Conflict (4th index)
[['Y', 'Y', 'Y'], ['Y', 'Y', 'Y'], ['Y', 'Y', 'Y']]
]

but my actual outcome changes the 4th index to:

[['R', 'R', 'R'], ['O', 'O', 'O'], ['O', 'O', 'O']]

I probably assume this to be because cube_g is updating in the for loop but I don't find a reason why. It is before the for loop. I even tried changing the variable names and adding new variables to avoid any inconsiderable reasons, but nothing seems to work! Any ideas as to why this might happen?


Solution

  • You're referencing the original cube when assigning it to cube_g, you have to make a copy with .copy()

    This should work:

    def cube_rotation(rotation):
        if 'U' in rotation:
            cube_g = cube[1].copy()
            direction = 1
            if '\'' in rotation: direction = -1;
            for i in range(1,4):
                cube[i][0] = cube[i+direction][0];
            cube[4][0] = cube_g[0];
        print(cube)
    cube_rotation('U')