# [Tutor] Re: Percolation model in python

Lee Harr missive at hotmail.com
Tue Feb 8 00:48:36 CET 2005

```>   I have two questions. Once a MxN world is generated how would you
>search for nearest neighbors (to see who is connected) and then color

Does this help?

import random

PERSON, EMPTY = '*', '.'

def get_threshold():
perc = raw_input("Please enter a thresold between 0-1.   ")
perc = float(perc)
return perc

def make_random_world(M, N):
"""Constructs a new random game world of size MxN."""
perc = get_threshold()
world = {}
for j in range(N):
for i in range(M):
world[i, j] = percolation(perc)
world['dimensions'] = (M, N)
return world

def percolation(perc):
randval = random.random()
if randval > perc:
return EMPTY
else:
return PERSON

def neighbors(world, x, y):
M, N = world['dimensions']
nxmin = max(0, x-1)
nxmax = min(M, x+1)
nymin = max(0, y-1)
nymax = min(N, y+1)
r = []
for nx in range(nxmin, nxmax+1):
for ny in range(nymin, nymax+1):
if nx != x or ny != y:
r.append((nx, ny))
return r

def print_world(world):
"""Prints out a string representation of a world."""
M, N = world['dimensions']
for j in range(N):
for i in range(M):
print world[i, j],
print

def make_world_option():
m = int(raw_input("Please enter a m dimension.   "))
n = int(raw_input("Please enter a n dimension.   "))

return make_random_world(m, n)

def show_neighbors_option(world):
x = int(raw_input("Please enter an x coord.   "))
y = int(raw_input("Please enter a y coord.   "))

print neighbors(world, x, y)

print """
1) Percolation model for Small Pox
2) Show world
3) Instructions
4) Show neighbors
5) Exit
"""

option = int(raw_input("Which option[1,2,3,4,5]? "))
return option

if __name__ == '__main__':

option = None
while option != 5:
if option == 1:
world = make_world_option()
elif option == 2:
print_world(world)
elif option == 4:
show_neighbors_option(world)