Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
regex grid solution in Clear category for Crossword Solver by DiZ
import re
def solver(crossword, words):
# Sort words by len
len_dict = {}
for word in words:
len_dict.setdefault(len(word), []).append(word)
for length, words in len_dict.items():
len_dict[length] = ' '.join(words)
# Scan crosswords
blanks, transposed = set(), list(map(''.join, zip(*crossword)))
for n, line in enumerate(list(crossword) + transposed):
is_column = n >= len(crossword)
step, i = 2 * is_column - 1, n - len(crossword) * is_column
for word in re.finditer('\.{3,}', line):
blanks.add(tuple((j, i)[::step] for j in range(*word.span())))
#Choose word order by flooding grid
grid, order = set(), []
while blanks:
next_word = max(blanks, key=lambda word: len(set(word) & grid))
blanks.discard(next_word)
grid.update(next_word)
order.append(next_word)
# Search word by word
def recursive(index, grid, restricted):
if not index: yield grid
blank = order[-index]
for word in re.finditer(''.join(map(grid.get, blank)), len_dict[len(blank)]):
word = word.group()
if word in restricted: continue
new_grid = grid.copy()
new_grid.update(zip(blank, word))
yield from recursive(index - 1, new_grid, restricted | {word})
# Fill crosswords
solutions = recursive(len(order), dict.fromkeys(grid, '\w'), set())
crossword = list(map(list, crossword))
for (i, j), char in next(solutions).items():
crossword[i][j] = char
return list(map(''.join, crossword))
March 6, 2015
Comments: