Computer Science question (python list is slow with my cruddy algorithm )

Thomas Jensen spam at ob_scure.dk
Fri Aug 23 13:22:34 CEST 2002


Mr. Neutron wrote:

> Now that that is out of the way, are there any better ways to represent
> the world than a list of lists? I just need to be able to say
> World[Y][X] = ( values ). Or be able to say what is at World[Position].
> Ideally I could say World[ (X,Y) ] = (Values) but I have not tried this.
> If World[ (X,Y) ] is empty, than it does not need to store anything in
> memory at all. I need to go to Idle now and experiment with this.

This class should get you started, it uses a dictionary to store the 
world. It only uses memory for those fields that are different from the 
default.
(And yes __str__ method is complicated, I hope someone can come up with 
a more readable way)

---------------
   class World:
     def __init__(self, width, height, default):
       self.width = width
       self.height = height
       self.default = default
       self.worlddata = {}

     def __getitem__(self, position):
       if (position[0] >= self.width) or (position[1] >= self.height):
         raise KeyError('position %s out of range' % repr(position))
       return self.worlddata.get(position, self.default)

     def __setitem__(self, position, value):
       if (position[0] >= self.width) or (position[1] >= self.height):
         raise KeyError('position %s out of range' % repr(position))
       self.worlddata[position] = value

     def __str__(self):
       return '\n'.join([''.join([str(self[x, y]) for x in 
range(self.width)]) for y in range(self.height)])
---------------

Example usage:

   my_world = World(32, 16, '#')
   my_world[4, 3] = '@'
   my_world[10, 2] = ' '
   my_world[21, 12] = '*'
   print my_world



-- 
Best Regards
Thomas Jensen
(remove underscore in email address to mail me)




More information about the Python-list mailing list