newbie question about dictionnary ?
Alex Martelli
aleax at aleax.it
Fri Sep 5 04:26:48 EDT 2003
Sophie Alléon wrote:
> Hi,
>
> CONTEXT
> I do numerical simulation for which I have to process mesh. A mesh is made
> of triangle which are made of points.
> I want from this information to create edges and build triangle from edges
> rather than from points.
>
> PROBLEM
> An edge is shared by possibly more than one triangle.
>
> ALGORITHM
> have a triangle class (made of 3 edges)
> have an edge class (made of 2 points and embeding a triangle list
> (those connected to the edge)
OK, so, say for example (for 2-D meshes):
import operator
class Point(tuple):
"""
a convenience class Point, basically just a 2-items (x,y) tuple
with handy constructor, accessors, representation
"""
__slots__ = ()
def __new__(cls, x, y):
# assert operator.isNumberType(x) and operator.isNumberType(y)
return tuple.__new__(cls, (x,y))
def getx(self): return self[0]
def gety(self): return self[1]
x = property(getx)
y = property(gety)
def __repr__(self): return "Point(%r,%r)" % self
class Edge(tuple):
"""
basically a 2-items tuple of points (NB: sorted, since we do
NOT deal with DIRECTED edges here!!!) with convenience
constructor, accessors, representation, + list of triangles
"""
def __new__(cls, p1, p2):
pts = [Point(*p1), Point(*p2)]
pts.sort()
return tuple.__new__(cls, pts)
def __init__(self, p1, p2):
self.triangles = []
def __repr__(self):
return 'Edge((%r,%r),(%r,%r))' % (self[0]+self[1])
The Triangle class may of course be made along very similar lines.
A slightly more efficient representation of Edge might use containment
of and delegation to tuple rather than inheriting from it (problem is
that inheriting from tuple impedes using a non-empty __slots__, so in
this code each Edge instance carries around an instance dictionary).
An even more clever approach might be to keep the edge->triangle data
NOT as per-instance data of edges but as a class-level attribute and
use a property for edge.triangles access, but that would violate the
explicit specs you give for the edge class.
> for each triangle construct its edges but I have to check if the edge
> already exists
>
> for doing this I thought the dictionary was excellent but the key is a
> string while I want it
> to be the 2 points forming the edge ? How to do it ?
>
> Have you a better idea ?
Strings just don't enter the picture here: edges are perfectly
acceptable keys into dictionaries, since they ARE tuples.
I do think that not having each edge 'embeding a triangle list',
as you put it, is an even better idea. But, although a bit more
complicated and less efficient, your idea can also work fine.
And, yes, of course you need a dictionary (in fact that is why
it's better to not ALSO have the triangle list IN the edge
instance -- it might as well be in the dictionary anyway... !!!).
Alex
More information about the Python-list
mailing list