coords = zip(clist[0::2],clist[1::2])
Sets also come with efficient union and intersection methods, which came up a few posts back. But they're unordered collections, and I'm uneducated-guessing that they might need a little more memory overhead, and so it might take a little more time to convert from a Golly cell list to a set of coordinates. Even a simple list of coordinates has the operators you need -- "in" and "remove".calcyman wrote:I would suggest using Python's built-in set container (of 2-tuples) instead of a list, since it has precisely the insertion, querying and deletion operations you require. Search for the emboldened words if you haven't encountered these data structures yet.
The detail that hasn't been addressed is how to get from a list of coordinates --
[[0,0], [0,1], [1,0], [1,2], [2,1]] or [(0,0), (0,1), (1,0), (1,2), (2,1)]
-- back to a simple Golly-compatible cell list. Golly doesn't accept nested lists like the above. So when you're all done membership-checking and adding and removing, you have to flatten the list again.
Extending the previous example:
Code: Select all
import golly as g
import itertools
g.setrule("Life")
clist = g.parse("12b3o$2bo5b2o2bo$b2o6b2o2bo$obo5bo$bo3$10b3o$12bo$11bo$18b3o$18bo$19bo!")
x,y = 18,11
coords = zip(clist[0::2],clist[1::2])
if (x,y) in coords:
coords.remove((x,y))
flatcells = list(itertools.chain.from_iterable(coords))
g.new("Result with cell removed")
g.putcells(flatcells)
flatcells = sum(coords,[])
# this is significantly slower for long coord lists,
# and it only works if coords are [x,y] lists, not (x,y) tuples
or
flatcells = reduce(list.__add__, (list(c) for c in coords))
# {converts from tuple to list if needed}
or (rumored to be among the fastest methods):
flatcells = []
map(flatcells.extend, coords)
That's lots more options than you need, of course. But you'll see most of these functions eventually in other contexts. It's nice to have an example of zip(), sum(), map(), extend(), reduce() and so on, doing something familiar and understandable.