Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Place Queens by UFO665
from itertools import product, combinations
verticals = "abcdefgh"
horizontals = "12345678"
def attackingFields(coord):
vc, hc = coord
vi, hi = verticals.index(vc), horizontals.index(hc)
return {v + h for h in horizontals for v in verticals if v + h != coord \
and (v == vc or h == hc or abs(verticals.index(v) - vi) == abs(horizontals.index(h) - hi))}
def isUnattacked(queens):
return all(all(q not in queens for q in attackingFields(queen)) for queen in queens)
def place_queens(queens):
lstVerticals = list(verticals)
lstHorizontals = list(horizontals)
for queen in queens:
v, h = queen
if v in lstVerticals:
lstVerticals.remove(v)
if h in lstHorizontals:
lstHorizontals.remove(h)
lstCoords = ["".join(c for c in p) for p in product(lstVerticals, lstHorizontals)]
lstCombinations = [c for c in combinations(lstCoords, len(lstVerticals)) \
if len({}.fromkeys([t[0] for t in c])) == len(c) and len({}.fromkeys([t[1] for t in c])) == len(c)]
for c in lstCombinations:
newQueens = queens.union(set(c))
if isUnattacked(newQueens):
return newQueens
return set()
Feb. 25, 2016