-1

I am currently attempting to program Conway's game of life, and am currently at the stage where I am simply attempting to initialize a randomized board.

I began by creating a list of 1000 elements, each one a list containing 1000 0s (essentially a 1000x1000 empty board).

The code I am using to update the 0s to 1s is the following:

def initialize(board):
    numlist=[1,2,3]
    for i,v in enumerate(board):
        for j,w in enumerate(v):
            if random.choice(numlist)==1:
                board[i][j]=1
    return board

However, when I run this function on the empty board noted above, every single value in the list is set to 1. I have also attempting to code this as the following:

def initialize(board):
    for i,v in enumerate(board):
        for j,w in enumerate(v):
            x=stats.uniform.rvs()
            if x<=.33:
                board[i][j]=1
    return board

I am having some trouble understanding why the output is a list of all 1s, instead of the desired output of the board where ~1/3 of the tiles are 1s. I have reviewed the code numerous times, and I am not seeing why this result keeps occurring.

How can I accomplish the goal I have put forth, namely assigning ~1/3 of the 1000x1000 tiles to be 1s? Any advice or guidance is greatly appreciated!

2 Answers2

0

I have determined that the answer was to turn the list of lists into a numpy array, that solved the problem right away!

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 04 '22 at 06:16
0

The error is probably with the original board that you passed in. If you started with something like:

board = [[0] * 1000] * 1000

then you have 1000 references to the same list, not 1000 different lists. Any modification you make is to the same shared list.

I'd initialize the board with something like:

board = [[random.choice([0, 0, 1]) for _ in range(1000)] for _ in range(1000)]

With a nested comprehension, the inner loop is executed multiple times inside the outer loop, giving you multiple unique lists; this is different from list multiplication, where the contents of the list are simply duplicated.

Samwise
  • 68,105
  • 3
  • 30
  • 44