Files
python/exercises/minesweeper/example.py

41 lines
1.2 KiB
Python
Raw Normal View History

def annotate(minefield):
if(minefield == []):
return []
verify_board(minefield)
row_len = len(minefield[0])
col_len = len(minefield)
board = [list(r) for r in minefield]
for index1 in range(col_len):
for index2 in range(row_len):
if board[index1][index2] != ' ':
2014-03-28 22:19:26 -03:00
continue
low = max(index2 - 1, 0)
high = min(index2 + 2, row_len + 2)
counts = minefield[index1][low:high].count('*')
if(index1 > 0):
counts += minefield[index1 - 1][low:high].count('*')
if(index1 < col_len - 1):
counts += minefield[index1 + 1][low:high].count('*')
if counts == 0:
2014-03-28 22:19:26 -03:00
continue
2015-11-08 09:07:52 +01:00
board[index1][index2] = str(counts)
return ["".join(r) for r in board]
2015-11-08 09:07:52 +01:00
def verify_board(minefield):
2014-03-28 22:19:26 -03:00
# Rows with different lengths
row_len = len(minefield[0])
if not all(len(row) == row_len for row in minefield):
2014-03-28 22:19:26 -03:00
raise ValueError("Invalid board")
2014-03-28 22:19:26 -03:00
# Unknown character in board
character_set = set()
for row in minefield:
character_set.update(row)
if character_set - set(' *'):
2015-11-08 09:07:52 +01:00
raise ValueError("Invalid board")