-2

While making a program that solves a Rubik's cube on python I wrote this bit of code for turning the front face of a Rubik's cube:

c_top = top
c_front = front
c_left = left
c_right = right
c_back = back
c_bottom = bottom
for x in range(6,9):
    right[x] = c_bottom[x]
    top[x] = c_right[x]
    left[x] = c_top[x]
    bottom[x] = c_left[x]    

For some reason it did something odd and changed c_bottom and other c_ things even though I only ran the function the code was in once. Does anyone know why?

fxwang
  • 3
  • 2

1 Answers1

1

It's because c_bottom and bottom are both variables referencing the same object. That means c_bottom[x] is the same as bottom[x] for every x in range(0, len(bottom)).

So when you do bottom[x] = c_left[x], c_bottom[x] also gets modified.

A simplified example:

a = ['Hello', 0, 0]
b = a

print(a[0]) # <<< Hello
b[0] = 'Goodbye'
print(a[0]) # <<< Goodbye

Edit: To solve this, you can either:

a) make c_side be a copy of side. If they're list, for example, you can do

c_bottom = list(bottom)

b) However, if you only want those c_side variables to perform that cycle, you can avoid doing copies with:

for x in range(6,9):
    right[x], top[x], left[x], bottom[x] = bottom[x], right[x], top[x], left[x]
Dleep
  • 1,045
  • 5
  • 12