8 Queens Problem

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Jul 10 03:58:04 EDT 2002


Duncan Booth <duncan at NOSPAMrcp.co.uk> wrote in
news:Xns9246AB0164B5Aduncanrcpcouk at 127.0.0.1: 

> Here are a couple of solutions based on your version but using
> generators. This has the advantage of giving you all the solutions for
> possible further processing, instead of just printing them out, and
> also allows you to avoid calculating all solutions if you just want
> one: 

I realised after posting that, I should have not tried to follow the 
structure of the original so closely. Here is (IMHO) a rather 
cleaner generator based solution:
---- queens.py ----
# 8 queens generator
from __future__ import generators
from operator import add, sub

def queens(col, row):
    '''Place 'col' queens on a grid col by row.
    Generates all possible solutions'''
    if col <= 1:
        for y in range(row): yield [(0, y)]
    else:
        x = col-1
        for solution in queens(x, row):
            t = zip(*solution)
            diaga, diags, rows = map(add, *t), map(sub, *t), t[1]
            for y in range(row):
                if x+y not in diaga and x-y not in diags and y not in rows:
                    yield solution + [(x, y)]

for s in queens(8,8):
    print s
    break

print len(list(queens(8,8))),"solutions"
---- end of queens.py ----

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list