Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 KB | None | 0 0
  1. def minesweeper(field):
  2.   """Takes a single string with newlines, consisting of '*' (mines) and other
  3.  characters (non-mines), and returns a string with numbers corresponding to the
  4.  number of mines around each cell.
  5.  
  6.  >>> print(minesweeper("...*.\n....."))
  7.  001*1
  8.  00111
  9.  
  10.  Hint for the algorithm: a cell is either a mine or a count of mines around it.
  11.  """
  12.  
  13.   lines = field.splitlines()
  14.   rows = len(lines)
  15.   cols = len(lines[0]) if rows > 0 else 0
  16.  
  17.   def isMine((r,c)):
  18.     return lines[r][c] == '*'
  19.  
  20.   def neighbours((r,c)):
  21.     return [(rr,cc) for rr in range(max(0,r-1), min(r+2, rows))  # r+2 here since
  22.                     for cc in range(max(0,c-1), min(c+2, cols))] # range() is not inclusive
  23.  
  24.   def count(cell):
  25.     return '*' if isMine(cell) else str(
  26.         sum([1 if isMine(neighbour) else 0 for neighbour in neighbours(cell)]))
  27.  
  28.   def join(strings):
  29.     return reduce(lambda x, y: x+y, strings)
  30.  
  31.   def toField(nums):
  32.     return '' if len(nums) == 0 else join(nums[0:cols]) + '\n' + toField(nums[cols:])
  33.  
  34.  
  35.   cells = [(r,c) for r in range(rows) for c in range(cols)]
  36.  
  37.   return toField(map(count, cells))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement