I have a list of rectangles stored as points. Currently, the data looks something like this:
boxes = [{'p1': (0,0), 'p2': (100,20)},
{'p1': (5,5), 'p2': (15,15)},
{'p1': (20,5), 'p2': (30,15)},
{'p1': (35,5), 'p2': (45,15)},
{'p1': (70,5), 'p2': (80,15)}]
I also have a basic function that tests if a rectangle is contained within another:
def isChild(b1,b2):
return (b1 != b2 and
(b1['p2'][0]-b1['p1'][0] * b1['p2'][1]-b1['p1'][1]) > (b2['p2'][0]-b2['p1'][0] * b2['p2'][1]-b2['p1'][1]) and
b1['p1'][0] < b2['p2'][0] and
b1['p2'][0] > b2['p1'][0] and
b1['p1'][1] < b2['p2'][1] and
b1['p2'][1] > b2['p1'][1])
I’d like to wind up with a set of rectangles and their children, but I’m not sure how I should store them. I’m thinking something like this:
[{'p1': (0,0),
'p2': (100,20),
'children': [{'p1': (5,5), 'p2': (15,15)},
{'p1': (20,5), 'p2': (30,15)},
{'p1': (35,5), 'p2': (45,15)},
{'p1': (70,5), 'p2': (80,15)}]}]
The context of this is that the boxes represent elements on a web page. The data structure is meant to generate the basic markup, so the structure above would wind up being something like this:
<div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
- Are the source/goal data structures a good fit for this? If not, what is?
- How can I get from the source to the goal?
- A friend suggested using r-trees. Would that make sense here?
Use classes. This is a typical usecase for OO programming. Create a class Rectangle
The class consist of two points, _p1 and _p2, and a list of children. The logic of finding parent-child relation goes into a method of this class (btw, does your method work? I changed it, as it returned nonsense for me. Maybe I have a different understanding of how the rectangle is defined.)
As you’re talking about websites and
<div>, I assume you won’t have thousands of rectangles. So this approach should be fine.This example can also be extended to plot all rectangles, so one can check the rectangles and the calculated kinship. Keeping class Rectangle unchanged, one can write:
This gives a plot like:

For this example, exactly one Rectangle had a child (violet is a child of green).