-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboard.py
382 lines (357 loc) · 10.8 KB
/
board.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
class Board:
""" An object to represent a 2-Dimensional rectangular board
"""
def __init__(self, num_cols=10, num_rows=20, cell_item=None, grid=None):
""" Create a Board instance that has num cols and num rows.
The 2D board is represented with a single list, if the board looks like:
col col col
0 1 2
-------------
| 0 | 1 | 2 | row 0
----+---+----
| 3 | 4 | 5 | row 1
-------------
Where num cols = 3, num rows = 2
Then the underlying representation looks like:
[0, 1, 2, 3, 4, 5]
Parameters
----------
num_cols (int, required):
number of columns. Defaults to 10.
num_rows (int, required):
number of rows. Defaults to 20.
cell_item (any, optional):
create default items. Defaults to None.
grid (list[any], optional): a list to create the underlying board representation.
However len(grid) = num_cols * num_rows. Defaults to None.
"""
assert num_cols is not None and num_rows is not None
assert type(num_cols) == int and type(num_rows) == int
assert num_cols >= 0 and num_rows >= 0
self._num_rows = num_rows
self._num_cols = num_cols
if grid:
assert num_cols * num_rows == len(grid)
self._grid = grid[:]
else:
self._grid = [cell_item for _ in range(num_cols * num_rows)]
# ---------------------------------------------------------------------------- #
# --------------------------------- Required --------------------------------- #
# ---------------------------------------------------------------------------- #
def get_col(self, x):
"""Get a copy of column x
Parameters
----------
x (int):
column number
Returns
-------
list[any]:
a list copy of column x
>>> board = Board(3, 2, grid=[7, 6, 3, 9, 5, 2])
>>> print(board)
=====
7 6 3
9 5 2
=====
>>> board.get_col(1)
[6, 5]
>>> board2 = Board(2, 2, grid=[1, 0, 4, 3])
>>> print(board2)
===
1 0
4 3
===
>>> board2.get_col(0)
[1, 4]
"""
# TODO: your solution here
def get_item(self, x, y):
"""Get the item at coordinate (x, y)
Parameters
----------
x (int):
column number
y (int):
row number
Returns
-------
any:
actual item
>>> board = Board(3, 2, grid=[5, 4, 1, 3, 0, 6])
>>> print(board)
=====
5 4 1
3 0 6
=====
>>> [board.get_item(x, y) for y in range(2) for x in range(3)]
[5, 4, 1, 3, 0, 6]
>>> board2 = Board(4, 1, grid=[9, 2, 4, 1])
>>> print(board2)
=======
9 2 4 1
=======
>>> [board2.get_item(x, y) for y in range(1) for x in range(4)]
[9, 2, 4, 1]
"""
# TODO: your solution here
def set_item(self, x, y, item):
"""Overwrite the item at (x, y)
Parameters
----------
x (int):
column number
y (int):
row number
item (any):
new item
>>> board = Board(3, 2, grid=[i for i in range(6)])
>>> print(board)
=====
0 1 2
3 4 5
=====
>>> board.set_item(0, 1, 30)
>>> board.set_item(2, 0, 11)
>>> print(board)
=====
0 1 11
30 4 5
=====
"""
# TODO: your solution here
def insert_row_at(self, y, lst):
"""Insert lst as new row at row y. Increment num_rows by 1
Parameters
----------
y (int):
row number
lst (list[any]):
list of row items
>>> board = Board(3, 2, grid=list(range(6)))
>>> print(board)
=====
0 1 2
3 4 5
=====
>>> board.insert_row_at(1, [6, 7, 8])
>>> print(board)
=====
0 1 2
6 7 8
3 4 5
=====
>>> board.get_num_rows()
3
"""
self._num_rows += 1 # DO NOT touch this line
# TODO: your solution here
def valid_coordinate(self, coordinate):
"""Check if coordinate (x, y) is within the board
Parameters
----------
coordinate (tuple(x, y)):
an (x: int, y: int) coordinate
Returns
-------
bool:
if the coordinate is valid within *this* board
>>> board = Board(3, 2, grid=list(range(6)))
>>> print(board)
=====
0 1 2
3 4 5
=====
>>> sum([board.valid_coordinate((x, y)) for x in range(3) for y in range(2)]) == 6
True
>>> board.valid_coordinate((2, 1))
True
>>> board.valid_coordinate((1, 1))
True
>>> board.valid_coordinate((0, 2))
False
>>> board.valid_coordinate((0, -1))
False
>>> board.valid_coordinate((-1, 0))
False
>>> board.valid_coordinate((3, 0))
False
"""
# TODO: your solution here
# ---------------------------------------------------------------------------- #
# --------------------------- Helpers: Not Required -------------------------- #
# ---------------------------------------------------------------------------- #
def get_row(self, y):
"""Get a copy of row y
Parameters
----------
y (int):
row number
Returns
-------
list[any]:
A list copy of row y
>>> board = Board(3, 2, grid=[i for i in range(6)])
>>> print(board)
=====
0 1 2
3 4 5
=====
>>> board.get_row(0)
[0, 1, 2]
>>> board.get_row(1)
[3, 4, 5]
"""
assert 0 <= y < self._num_rows, f'Invalid y: {y}'
start_index = y * self._num_cols
return self._grid[start_index : start_index + self._num_cols]
def delete_row(self, y):
"""Delete row y and decremet num_rows count by 1
Parameters
----------
y (int):
row number
>>> board = Board(3, 3, grid=list(range(9)))
>>> print(board)
=====
0 1 2
3 4 5
6 7 8
=====
>>> board.delete_row(1)
>>> print(board)
=====
0 1 2
6 7 8
=====
>>> board.get_num_rows()
2
"""
index_start = y * self._num_cols
del self._grid[index_start : index_start + self._num_cols]
self._num_rows -= 1
def index_to_coordinate(self, index):
"""Convert an index to (x, y) coordinate
Parameters
----------
index (int):
index in underlying list representation
Returns
-------
tuple[int, int]:
tuple coordinate
>>> board = Board(3, 2, grid=[i for i in range(6)])
>>> print(board)
=====
0 1 2
3 4 5
=====
>>> board.index_to_coordinate(5)
(2, 1)
"""
assert 0 <= index < len(self._grid), f'Invalid index: {index}'
return (index % self._num_cols, index // self._num_cols)
def filter_coordinates(self, fn):
"""Extract coordinates of all item that satisfy fn and returns
a list of these coordinates in tuples
Parameters
----------
fn (any -> bool):
a boolean function that operates on items of *this* board
Returns
-------
list[tuple[int, int]]:
a list of tuple coordinates
>>> board = Board(3, 3, grid=[i for i in range(9)])
>>> board.filter_coordinates(lambda x: x % 2 == 1)
[(1, 0), (0, 1), (2, 1), (1, 2)]
"""
return [(i % self._num_cols, i // self._num_cols) \
for i, item in enumerate(self._grid) if fn(item)]
def update_grid(self, new_grid):
""" Overwrite existing underlying board with a new board
"""
assert len(new_grid) == len(self._grid), 'unequal grid lengths'
self._grid = new_grid
def get_num_rows(self):
return self._num_rows
def get_num_cols(self):
return self._num_cols
def get_grid(self):
""" Returns a COPY of the underlying grid
"""
return self._grid[:]
def __contains__(self, item):
""" Returns True if item is in this Board, False otherwise
>>> board = Board(2, 3, grid=list(range(6)))
>>> 5 in board
True
>>> 6 in board
False
"""
return self._grid.__contains__(item)
def __getitem__(self, key):
""" Using bracket notation e.g. [, ] and pass in either a number
or a coordinate.
>>> board = Board(3, 5, '*')
>>> board[4] == board[(1, 1)] == board[[1, 1]] == '*'
True
"""
if isinstance(key, int):
return self._grid[key]
return self.get_item(key[0], key[1])
def __setitem__(self, key, value):
""" Using bracket notation e.g. [, ] and pass in either a number
or a coordinate.
>>> board = Board(3, 5, '*')
>>> board[7] = 70
>>> board.get_item(1, 2)
70
"""
if isinstance(key, int):
self._grid[key] = value
else:
self.set_item(key[0], key[1], value)
def __iter__(self):
""" Iterate through the underlying grid in row major order
>>> board = Board(2, 2, grid=list(range(4)))
>>> list(board)
[0, 1, 2, 3]
"""
return self._grid.__iter__()
def __reversed__(self):
""" Iterate through the underlying grid in reverse row major order
Use the built-in reversed() call.
>>> board = Board(2, 2, grid=list(range(4)))
>>> list(reversed(board))
[3, 2, 1, 0]
"""
return self._grid.__reversed__()
def __len__(self):
""" Returns the total number of elements
>>> board = Board(3, 3, grid=list(range(9)))
>>> len(board)
9
"""
return self._grid.__len__()
def __repr__(self):
return f'<Board num_cols: {self._num_cols} num_rows: {self._num_rows}>'
def __str__(self):
""" Print out the board items in a grid
>>> board = Board(2, 3, grid=list(range(6)))
>>> print(board)
===
0 1
2 3
4 5
===
"""
s = '=' * (self._num_cols * 2 - 1) + '\n'
for i, val in enumerate(self._grid):
s += str(val)
if (i + 1) % self._num_cols != 0:
s += ' '
if (i + 1) % self._num_cols == 0:
s += '\n'
s += '=' * (self._num_cols * 2 - 1)
return s