Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def minesweeper(field):
- """Takes a single string with newlines, consisting of '*' (mines) and other
- characters (non-mines), and returns a string with numbers corresponding to the
- number of mines around each cell.
- >>> print(minesweeper("...*.\n....."))
- 001*1
- 00111
- Hint for the algorithm: a cell is either a mine or a count of mines around it.
- """
- lines = field.splitlines()
- rows = len(lines)
- cols = len(lines[0]) if rows > 0 else 0
- def isMine((r,c)):
- return lines[r][c] == '*'
- def neighbours((r,c)):
- return [(rr,cc) for rr in range(max(0,r-1), min(r+2, rows)) # r+2 here since
- for cc in range(max(0,c-1), min(c+2, cols))] # range() is not inclusive
- def count(cell):
- return '*' if isMine(cell) else str(
- sum([1 if isMine(neighbour) else 0 for neighbour in neighbours(cell)]))
- def join(strings):
- return reduce(lambda x, y: x+y, strings)
- def toField(nums):
- return '' if len(nums) == 0 else join(nums[0:cols]) + '\n' + toField(nums[cols:])
- cells = [(r,c) for r in range(rows) for c in range(cols)]
- return toField(map(count, cells))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement