Home > other >  Assigning values to elements of a list based on random choice
Assigning values to elements of a list based on random choice

Time:05-03

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!

CodePudding user response:

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

CodePudding user response:

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)]
  • Related