8 queen/game of life

Remco Gerlich scarblac-spamtrap at pino.selwerd.nl
Thu Jun 15 04:21:33 EDT 2000


root at sirius.ftsm.ukm.my wrote in comp.lang.python:
> 1. conway's game of life:
>    how to have a matrix in python? 
>    the following is not good;
>    
>            r0=[0,0,0]
> 	   r1=[0,0,0]
> 	   ........
> 	   
> 	   m=[r0,r1,....]
> 
>    the matrix is fixed, which is not good.

So just use a loop to do the same thing.

m = []
for i in range(8):
   m.append([0]*8)
   
Makes a 8*8 list of lists.

> my solution use dictionary (i know this is not the right way). 

It works, it's not very critical here, I'd say that's good enough too.

> 2. 8 non-attacking queen.
> 
>    use backtracking. the function call itself back. how to do recursive call
>    in python?

Well, just call the function.

>    roughly, the C program I study look like this;
>    
>    queen_count = -1
>    
>    main()
>    {
>      addqueen();
>    }
>    
>    addqueen()
>    {
>    queen_count++
>    if queen_count != 8
>         addqueen()
>    else
>         print result
>    }
> 	
>    how to pass a global variable (queen_count) to a function?

By default, if you assign to a variable inside a function, Python assumes it
is a local. If you never change it but only use it read-only, Python assumes
it's a global. If you want to use the global, use the 'global <varname>'
statement.

Your program would become something like:

queen_count = -1

def add_queen():
   global queen_count
   
   queen_count = queen_count+1
   if queen_count != 8:
      add_queen()
   else:
      print result # It would die here of course, 'result' is unknown

if __name__ == '__main__':
   add_queen()


(The last two lines is the common way to do a 'main()' sort of thing; it
only runs if the script is run as the main program; if some other module
imports it, it doesn't run).

-- 
Remco Gerlich,  scarblac at pino.selwerd.nl
 10:19am  up 100 days, 22:32,  7 users,  load average: 0.24, 0.12, 0.21



More information about the Python-list mailing list