Skip to content

Instantly share code, notes, and snippets.

@sma
Created September 30, 2009 12:08
Show Gist options
  • Save sma/198051 to your computer and use it in GitHub Desktop.
Save sma/198051 to your computer and use it in GitHub Desktop.
class ListOfListArray:
def __init__(self, width, height, default=None):
self.width, self.height = width, height
self.values = [[default] * width for i in range(height)]
def __getitem__(self, (x, y)):
return self.values[y][x]
def grow_height(self, dy, default=None):
self.height += dy
self.values.extend([default] * self.width for i in range(dy))
def grow_width(self, dx, default=None):
self.width += dx
for row in self.values:
row.extend([default] * dy)
def SingleListArray:
def __init__(self, width, height, default=None):
self.width, self.height = width, height
self.values = [default] * (width * height)
def __getitem__(self, (x, y)):
if 0 <= x < self.width:
return self.values[x + self.width * y]
raise IndexError
def grow_height(self, dy, default=None):
self.height += dy
self.values.extend([default] * (dy * self.width))
def grow_width(self, dx, default=None):
new_width = self.width + dx
new_values = [default] * (new_width * self.height)
for y in range(self.height):
for x in range(self.width):
values[x + new_width * y] = self[x, y]
self.values = new_values
self.width = new_width
class DictArray:
def __init__(self, width, height, default=None):
self.width, self.height, self.default = width, height, default
self.values = {}
def __getitem__(self, (x, y)):
if 0 <= x < self.width and 0 <= y < self.height:
return self.values.get((x, y), default)
raise IndexError
def grow_height(self, dy): self.height += dy
def grow_width(self, dx): self.width += dx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment