[Tutor] Making Doubly Linked List with Less Lines of Code.
Dave Angel
davea at davea.name
Fri Jan 2 06:28:38 CET 2015
On 01/01/2015 11:48 PM, WolfRage wrote:
> Final Code Using 2d List instead of Doubly Linked List.
>
>
Please don't top-post. Instead, post your comments inline with the
parts of the previous message to which you're responding.
Is there a reason you doublespaced the whole thing? And why did you
retype it instead of just copy/pasting it? And why lose the
indentation, so nobody can actually try it without guessing at your
indentation?
> class GameTile():
>
> def __init__(self, id, **kwargs):
>
> # id is (X,Y)
>
> self.id = id
>
>
> class GameGrid():
>
> def __init__(self, **kwargs):
>
> self.cols = 7
>
> self.rows = 8
These two would more generally have been parameters, and you'd create
the grid by specifying the sizes to be used.
>
> # grid is 2d array as y, x ie [y][x].
>
> self.grid = [[None] * self.rows for i in range(self.cols)]
>
If you always call make_grid immediately after constructing the grid,
then why not combine __init__ with make_grid? It'd be much shorter.
>
>
> def make_grid(self):
>
> for row in range(0, self.rows):
>
> for col in range(0, self.cols):
>
> self.grid[col][row] = GameTile(id=str(row) + ',' + str(col))
>
>
>
> def print_by_row(self):
>
> for col in range(0, self.cols):
>
> for row in range(0, self.rows):
>
> print(self.grid[col][row].id)
>
This could be better written as:
for col in self.grid:
for row in col
print row.id
>
>
> def print_by_col(self):
>
> for row in range(0, self.rows):
>
> for col in range(0, self.cols):
>
> print(self.grid[col][row].id)
>
likewise, but it's a bit trickier.
>
> def check_bounds(self, x, y):
>
> if (0 <= x < self.rows) and (0 <= y < self.cols):
>
> return True
>
> return False
This could be simplified to just:
return (0 <= x < self.rows) and (0 <= y < self.cols)
>
>
> def lookup_node(self, x, y):
>
> if not self.check_bounds(x, y):
>
> return False
>
> return self.grid[y][x]
>
>
> def draw_grid(self):
>
> for col in range(0, self.cols):
>
> print(end='| ')
>
> for row in range(0, self.rows):
>
> print(self.grid[col][row].id, end=' | ')
>
> print()
>
>
>
> temp = GameGrid()
>
temp = GameGrid(8, 7)
> temp.make_grid()
>
> temp.draw_grid()
>
--
DaveA
More information about the Tutor
mailing list