Reputation: 59
I have a grid for a game set out as below:
grid = [(0,0,0,0,0,0,0),
(0,0,0,0,0,0,0),
(0,0,0,0,0,0,0),
(0,0,0,0,0,0,0),
(0,0,0,0,0,0,0)]
I need to iterate through the outer cells of the grid and randomly turn them into either "1" or "0".
Is there a way of doing this quickly whilst maintaining the ability to change the size of the grid and still perform the same thing?
thanks in advance!
Upvotes: 1
Views: 113
Reputation: 1520
You should use arrays through numpy module to improve performances as follow:
import numpy as np
from random import randint
def random_grid():
while True:
grid = np.array([randint(0, 1) for _ in range(35)]).reshape(5,7)
yield grid
gen_grids = random_grid()
print gen_grids.next()
Upvotes: 0
Reputation: 4255
First of all you should use lists instead of tuples, tuples are immutable and cannot be changed.
Create grid as list with lists
grid = [[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]
This should do the trick, though one of the python-gurus may have an even easier solution.
First Edition
#go through all the lines
for index, line in enumerate(grid):
#is the line the first or the last one
if index == 0 or index == len(grid)-1:
#randomize all entries
for i in range(0, len(line)):
line[i] = randint(0, 1)
#the line is one in the middle
else:
#randomize the first and the last
line[0] = randint(0, 1)
line[-1] = randint(0, 1)
After toying around some more I could replace the nested for with a list comprehension to make the code more readable
Second Edition
for index, line in enumerate(grid):
if index == 0 or index == len(grid)-1:
grid[index] = [randint(0, 1)for x in line]
else:
line[0] = randint(0, 1)
line[-1] = randint(0, 1)
If someone points out an easier/more readable way to do the if I would be glad.
Upvotes: 2
Reputation: 745
Extending Jan's answer
from random import randint
grid = [[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0]]
for x, j in enumerate(grid):
for y, i in enumerate(j):
grid[x][y] = randint(0,1)
print(grid)
This is a simple solution independent of whatever is the size, but if performance is critical, then go for numpy.
Upvotes: 0
Reputation: 1220
You can use numpy , and you don't need to iterate at all .
import numpy as np
grid = np.array([(0,0,0,0,0,0,0),
(0,0,0,0,0,0,0),
(0,0,0,0,0,0,0),
(0,0,0,0,0,0,0),
(0,0,0,0,0,0,0)])
grid[[0,-1]] = np.random.randint(2,size=(2,grid.shape[1]))
grid[:,[0,-1]] = np.random.randint(2,size=(grid.shape[0],2))
Upvotes: 0
Reputation: 1439
If you represent your grid as a list of lists (rather than a list of tupples), then it's a matter of iterating over the outer cells and setting:
grid[x][y] = random.randint(0, 1)
... considering that by "randomly turn them" you mean "change them with 50% probability".
Upvotes: 1