8 Queens Problem
Joseph A Knapka
jknapka at earthlink.net
Tue Jul 9 16:31:40 EDT 2002
Simon.Foster at smiths-aerospace.com wrote:
>
> Just For Fun!
>
> I've been working on a solution to the eigth queens puzzle.
> Here is my attempt. There's a solution in Scheme in SICP
> which takes only 13 lines. Can anyone come up with a shorter
> solution in Python, without any of the obvious silliness?
Sure :-)
from operator import add
size=8
def attacks((r1,c1),(r2,c2)): return ((r1,c1) != (r2,c2)) and ((r1==r2)
or (abs(r1-r2)==abs(c1-c2)))
def check(n):
qpos = map(lambda c: ((n/(size**c))%size,c),range(size))
return reduce(add,[reduce(add,[attacks(qpos[q],qpos[o]) for o in
range(size)]) for q in range(size)])
for n in xrange(size**size):
if not check(n): print "Solution:",map(lambda c:
((n/(size**c))%size,c),range(size))
It gives you the coordinates of the queens' board
positions, and finds all solutions by exhaustive search.
It isn't exactly fast, though. Set size=4 to solve
the 4-queens problem before you die. It exchanges
obvious silliness for obscure silliness. I'm sure Alex
can improve this lots.
Cheers,
-- Joe
More information about the Python-list
mailing list