Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Nonogram Row by PythonLearner
import re
from itertools import combinations
UNKNOWN_CELL_MARKER = '?'
FILLED_CELL_MARKER = 'O'
EMPTY_CELL_MARKER = 'X'
def get_variants(row_string, clue_numbers):
filled_segments = [FILLED_CELL_MARKER*length for length in clue_numbers]
total_empty_fragments_length = len(row_string)-sum(clue_numbers)
for combination in combinations(range(total_empty_fragments_length+1), len(filled_segments)):
variant = []
used_empty_cells = 0
for i in range(len(filled_segments)):
empty_fragment_length = combination[i]-used_empty_cells
variant.append(EMPTY_CELL_MARKER*empty_fragment_length)
variant.append(filled_segments[i])
used_empty_cells += empty_fragment_length
variant.append(EMPTY_CELL_MARKER*(total_empty_fragments_length-used_empty_cells))
yield "".join(variant)
def nonogram_row(row_string, clue_numbers):
result = []
pattern = row_string.replace(UNKNOWN_CELL_MARKER, ".")
variants = filter(lambda variant: re.match(pattern, variant), get_variants(row_string, clue_numbers))
for column in zip(*variants):
if column.count(column[0]) == len(column):
result.append(column[0])
else:
result.append(UNKNOWN_CELL_MARKER)
return "".join(result) if result else None
if __name__ == '__main__':
assert nonogram_row('??????????', [8]) == '??OOOOOO??', 'Simple boxes_1'
assert nonogram_row('??????????', [4, 3]) == '??OO???O??', 'Simple boxes_2'
assert nonogram_row('???O????O?', [3, 1]) == 'X??O??XXOX', 'Simple spaces'
assert nonogram_row('????X?X???', [3, 2]) == '?OO?XXX?O?', 'Forcing'
assert nonogram_row('O?X?O?????', [1, 3]) == 'OXX?OO?XXX', 'Glue'
assert nonogram_row('??OO?OO???O?O??', [5, 2, 2]) == 'XXOOOOOXXOOXOOX', 'Joining and splitting'
assert nonogram_row('????OO????', [4]) == 'XX??OO??XX', 'Mercury'
assert nonogram_row('???X?', [0]) == 'XXXXX', 'Empty_1'
assert nonogram_row('?????', []) == 'XXXXX', 'Empty_2'
assert nonogram_row('??X??', [3]) is None, 'Wrong string'
print("Check done.")
Sept. 2, 2018
Comments: