How to use generators?

Ian Vincent i_vincent at hotmail.com
Wed Nov 9 06:18:12 EST 2005


<Spoiler Alert - Anyone at < Level 24 in Python Challenge may not want to 
read this post!>



I have never used generators before but I might have now found a use for 
them. I have written a recursive function to solve a 640x640 maze but it 
crashes, due to exceeding the stack.  The only way around this I can 
think of is to use Generator but I have no idea how to.

The function is as below:

def solve_maze(x,y):
    if y <= 0:
        success = 1
    elif x <= 0 or x > 640 or y >= 640:
        success = 0
    elif maze_array[x][y] == 1:
        success = 0
    elif im.getpixel((x,y)) == (255, 255, 255, 255):
        success = 0
    else:
        maze_array[x][y] = 1
        if solve_maze(x,y-1) == 1:
            success = 1
        elif solve_maze(x+1,y) == 1:
            success = 1
        elif solve_maze(x-1,y) == 1:
            success = 1
        else:
            success = solve_maze(x,y+1)

    if success == 1:
        print im.getpixel((x,y))

    return success

#Main
wibble = solve_maze(x,y)



More information about the Python-list mailing list