[Tutor] Making Doubly Linked List with Less Lines of Code.
WolfRage
wolfrage8765 at gmail.com
Fri Jan 2 05:48:18 CET 2015
Final Code Using 2d List instead of Doubly Linked List.
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
# grid is 2d array as y, x ie [y][x].
self.grid = [[None] * self.rows for i in range(self.cols)]
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)
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)
def check_bounds(self, x, y):
if (0 <= x < self.rows) and (0 <= y < self.cols):
return True
return False
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.make_grid()
temp.draw_grid()
Any feedback for my code is appreciated. Thank you.
On 12/31/2014 06:57 PM, Steven D'Aprano wrote:
> Trust me on this, there is no linked list code you can write in Python
> that will be faster than using a list of lists. Even in C, traversing
> a linked list is slower than array access, and Python is not C.
OK. I do trust you.
> Bounds checking is easy: cell [i, j] is in bounds if this is true:
>
> (0 <= i < NUM_ROWS) and (0 <= j < NUM_COLS)
>
> Fast access to any cell is possible:
>
> array[i][j]
Implemented both.
> from sys import getsizeof
Thanks I forgot about getsizeof.
More information about the Tutor
mailing list