[Tutor] Making Doubly Linked List with Less Lines of Code.

WolfRage wolfrage8765 at gmail.com
Fri Jan 2 17:37:12 CET 2015


On 01/02/2015 02:21 AM, Steven D'Aprano wrote:
> What is the purpose of the **kwargs? It doesn't get used, it just
> silently ignores them.

Hopefully you got the answer for this from the previous message.
>
> Why does the GameTile record the coordinates as strings?

Hopefully you got the answer for this from the previous message.
>
> Your lookup_node method returns a GameTile or False on failure:
>
>      def lookup_node(self, x, y, ):
>          if not self.check_bounds(x, y):
>              return False
>          return self.grid[y][x]
>
> I'm not sure about that design. I wonder whether it would be better to
> return None, or raise an exception.
What would you suggest this code does on error, when the Node looked up 
is out of bounds?

Latest copy of the code. I think I got every ones suggestion.

import sys


class GameTile():
     def __init__(self, col, row, **kwargs):
         # id is (X,Y)
         self.id = str(row) + ',' + str(col)
         self.col = col
         self.row = row

     def __str__(self):
         return '%d, %d' % (self.col, self.row)


class GameGrid():
     def __init__(self, cols=8, rows=7, **kwargs):
         self.cols = cols
         self.rows = rows
         self.make_grid()

     def make_grid(self):
         # grid is 2d array as x, y ie [x][y].
         self.grid = [[None] * self.cols for i in range(self.rows)]
         for row in range(self.rows):
             for col in range(self.cols):
                 self.grid[row][col] = GameTile(row=row, col=col)

     def print_by_row(self):
         for col in self.grid:
             for row in col:
                 print(row)

     def print_by_col(self):
         for row in self.grid:
             for col in row:
                 print(col)

     def check_bounds(self, x, y):
         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[x][y]

     def draw(self):
         for col in self.grid:
             print(end='| ')
             for row in col:
                 print(row, end=' | ')
             print()


grid = GameGrid(3, 3)
grid.draw()
print(sys.getsizeof(grid.grid))



More information about the Tutor mailing list