diff options
author | William Carroll <wpcarro@gmail.com> | 2020-02-08T12·01+0000 |
---|---|---|
committer | William Carroll <wpcarro@gmail.com> | 2020-02-08T12·01+0000 |
commit | 5ade510598e0104a103f0b8fe9ed84ad3c4b13dc (patch) | |
tree | 62e7d3a8738e90580f9af2b5857803df472fb616 | |
parent | c2971ee04ea1cde3e03095a66e0d28636d07eb64 (diff) |
Practice writing, printing, traversing matrices
- generate_board: writing - print_board: reading - neighbords: reading I'm working up to creating a function to initialize a game board where no three adjacent cells either vertically or horizontally should be the same value.
-rw-r--r-- | deepmind/part_two/matrix-traversals.py | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/deepmind/part_two/matrix-traversals.py b/deepmind/part_two/matrix-traversals.py index cd4a048d5219..52354f990e11 100644 --- a/deepmind/part_two/matrix-traversals.py +++ b/deepmind/part_two/matrix-traversals.py @@ -57,3 +57,48 @@ for row in reversed(board): for col in reversed(row): result.append(col) print(result) + +################################################################################ +# Neighbors +################################################################################ + +import random + + +# Generate a matrix of size `rows` x `cols` where each cell contains an item +# randomly selected from `xs`. +def generate_board(rows, cols, xs): + result = [] + for _ in range(rows): + row = [] + for _ in range(cols): + row.append(random.choice(xs)) + result.append(row) + return result + + +# Print the `board` to the screen. +def print_board(board): + print('\n'.join([' '.join(row) for row in board])) + + +board = generate_board(4, 5, ['R', 'G', 'B']) +print_board(board) + + +# Return all of the cells horizontally and vertically accessible from a starting +# cell at `row`, `col` in `board`. +def neighbors(row, col, board): + result = {'top': [], 'bottom': [], 'left': [], 'right': []} + for i in range(row - 1, -1, -1): + result['top'].append(board[i][col]) + for i in range(row + 1, len(board)): + result['bottom'].append(board[i][col]) + for i in range(col - 1, -1, -1): + result['left'].append(board[row][i]) + for i in range(col + 1, len(board[0])): + result['right'].append(board[row][i]) + return result + + +print(neighbors(1, 2, board)) |