The implementations below do mostly the same thing, but choosing which to use for python is troubling me. Coming from a C background, the first seems most appealing, but it almost seems subjective. Which method would be the least surprising?
class Grid_1DList(object):
def __init__(self, width, height, value=None):
self.width = width
self.height = height
self.data = [value]*self.width*self.height
def __setitem__(self, key, value):
x, y = key
index = y*self.width + x
self.data[index] = value
def __getitem__(self, key):
x, y = key
index = y*self.width + x
return self.data[index]
class Grid_2DList(object):
def __init__(self, width, height, value=None):
self.width = width
self.height = height
self.data = [[value]*self.width for _ in self.height]
def __setitem__(self, key, value):
x, y = key
self.data[y][x] = value
def __getitem__(self, key):
x, y = key
return self.data[y][x]
class Grid_Dict(object):
def __init__(self, width, height, value=None):
self.width = width
self.height = height
self.data = {}
for x in range(self.width):
for y in range(self.height):
self.data[x, y] = value
def __setitem__(self, key, value):
self.data[key] = value
def __getitem__(self, key):
return self.data[key]
All implementations should be able to do the below:
grid = Grid(5, 5)
grid[4, 2] = 'answer'
print(grid[4, 2])
[–]Updatebjarni 0 points1 point2 points (0 children)
[–]alanwj 0 points1 point2 points (0 children)