Trees

Devin Jeanpierre jeanpierreda at gmail.com
Tue Jan 20 00:52:41 CET 2015


On Mon, Jan 19, 2015 at 3:08 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> Zachary Gilmartin wrote:
>
>> Why aren't there trees in the python standard library?
>
> Possibly because they aren't needed? Under what circumstances would you use
> a tree instead of a list or a dict or combination of both?
>
> That's not a rhetorical question. I am genuinely curious, what task do you
> have that you think must be solved by a tree?

In general, any time you want to maintain a sorted list or mapping,
balanced search tree structures come in handy.

Here's an example task: suppose you want to represent a calendar,
where timeslots can be reserved for something. Calendar events are not
allowed to intersect.

The most important query is: What events are there that intersect with
the timespan between datetimes d1 and d2? (To draw a daily agenda,
figure out if you should display an alert to the user that an event is
ongoing or imminent, etc.)

You also want to be able to add a new event to the calendar, that
takes place between d1 and d2, and to remove a event.

I leave it to the reader to implement this using a sorted map. (hint:
sort by start.)

This maybe seems contrived, but I've used this exact datatype, or a
remarkably similar one, in a few different circumstances: sequenced
actions of characters in a strategy game, animation, motion
planning...

There are a few possible implementations using Python data structures.
You can do it using a linear scan, which gets a little slow pretty
quickly. You can make insertion slow (usually OK) by sorting on
insertion, but if you ever forget to resort your list you will get a
subtle bug you might not notice for a while. And so on. It's better in
every way to use the third-party blist module, so why bother?

-- Devin



More information about the Python-list mailing list