[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
        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],

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

    raw_input("Press return to make a world")
    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)

def menu():
    print """
    Please pick your option:
    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:
        elif option == 4:

        option = menu()

Don't just search. Find. Check out the new MSN Search! 

More information about the Tutor mailing list