eight-queens.py
from __future__ import print_function
from sys import stdin, stdout, stderr, argv
NROWS = 8
NCOLS = 8
CFG = [NROWS, NCOLS, 0]
str_accum = lambda acc: ':'.join(map(lambda x: str(x), accum))
def report_solution (fp, accum):
fp.flush()
fp.write(' %s:\n' % accum)
fp.write(' +')
for cx in range(CFG[1]):
fp.write('---+')
fp.write('\n')
for rx in range(CFG[0]):
row = rx + 1
fp.write(' |')
for cx in range(CFG[1]):
col = cx + 1
if accum[cx] == row:
fp.write(' Q |')
else:
fp.write(' |')
fp.write('\n')
fp.write(' +')
for cx in range(CFG[1]):
fp.write('---+')
fp.write('\n')
fp.write('\n')
fp.flush()
CFG[2] += 1
return CFG[2]
def test_queen (accum, row):
for ch in accum:
if ch == row:
return 0
for ix,ch in enumerate(reversed(accum)):
n = row + (ix + 1)
if CFG[0] < n:
break
if n == ch:
return 0
for ix,ch in enumerate(reversed(accum)):
n = row - (ix + 1)
if n < 1:
break
if n == ch:
return 0
return 1
def place_queen (fp, accum=[], col=1):
row = 1
while row <= CFG[0]:
if test_queen(accum, row):
accum.append(row)
if col == CFG[1]:
report_solution(fp, accum)
else:
place_queen(fp, accum, col+1)
accum.pop()
row += 1
if (col == 1) and (int((CFG[0]+1)/2) < row):
break
return CFG[2]
def do_test (*args):
print('test/parameters: %d' % len(args))
CFG[0] = int(args[0]) if 0 < len(args) else NROWS
CFG[1] = int(args[1]) if 1 < len(args) else NCOLS
fn = args[2] if 2 < len(args) else 'eight-queens.out'
fp = open(fn, 'w')
try:
place_queen(fp)
print(file=fp)
print("%d solution%s!" % (CFG[2], '' if CFG[2]==1 else 's'), file=fp)
print(file=fp)
except Exception as e:
raise
finally:
fp.close()
return 'Done!'
def do_main (*args):
print('main/parameters: %d' % len(args))
fn = args[0] if 0 < len(args) else 'eight-queens.out'
fp = open(fn, 'w')
try:
place_queen(fp)
print(file=fp)
print("%d solution%s!" % (CFG[2], '' if CFG[2]==1 else 's'), file=fp)
print(file=fp)
except Exception as e:
raise
finally:
fp.close()
return 'Done!'
def dispatch (cmd, *args):
print('command: %s' % cmd)
print('arguments: %d' % len(args))
if cmd == 'test': return do_test(*args)
if cmd == 'main': return do_main(*args)
return 'Nothing to do!'
if __name__ == '__main__':
print('autorun: %s' % argv[0])
cmd = argv[1] if 1 < len(argv) else ''
etc = argv[2:] if 2 < len(argv) else []
obj = dispatch(cmd, *etc)
print("%d solution%s!" % (CFG[2], '' if CFG[2]==1 else 's'))
print(obj)
'''eof'''