I have a class named Board, that is supposed to act as a 4x4 list of lists. However, in the init method, I don't create any list of lists and instead create a list with random numbers, with several restrictrions, and its named self.initial_numbers (its size varies from 2 to 4). The4x4 matrix is supposed to be created afterwards as a property, where a bunch of its elements will be equal to 0 and a couple of them, distributed randomly, will be filled in with the elements from self.initial_numbers:
@property
def rows(self):
rows = [[0]*4 for _ in range(4)]
for number in self.initial_numbers:
x, y = (randint(0, 3), randint(0, 3))
while rows[x][y] != 0:
x, y = (x+1) % 4, (y+1) % 4
rows[x][y] = number
return rows
The while cicle is there to guarantee that no elements from self.initial_numbers get attributed to the same position. In general, this property seems to be doing what I want, it creates a 4x4 matrix with a bunch of zeroes and some non-zero elements distributed randomly. However, it seems I can't index it properly. The code
r = Board()
print(r.rows)
print([x for x in r.rows])
returns
[[0, 0, 0, 0], [0, 0, 0, 2], [0, 0, 0, 2], [0, 0, 0, 2]]
[[0, 0, 0, 0], [2, 2, 0, 0], [0, 0, 0, 0], [0, 2, 0, 0]]
and if i try to do r.rows[0] for example, it returns a completely different sublist than the one I'm trying to index.
Aucun commentaire:
Enregistrer un commentaire