Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #84033

Re: Trees

References <mailman.17862.1421705173.18130.python-list@python.org> <54bd8e6a$0$13009$c3e8da3$5496439d@news.astraweb.com>
From Devin Jeanpierre <jeanpierreda@gmail.com>
Date 2015-01-19 15:52 -0800
Subject Re: Trees
Newsgroups comp.lang.python
Message-ID <mailman.17867.1421711603.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Jan 19, 2015 at 3:08 PM, Steven D'Aprano
<steve+comp.lang.python@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Trees Zachary Gilmartin <zacharygilmartin@gmail.com> - 2015-01-19 17:06 -0500
  Re: Trees Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-01-20 10:08 +1100
    Re: Trees Michael Torrie <torriem@gmail.com> - 2015-01-19 16:19 -0700
    Re: Trees Devin Jeanpierre <jeanpierreda@gmail.com> - 2015-01-19 15:52 -0800
    Re: Trees Tim Chase <python.list@tim.thechases.com> - 2015-01-19 18:00 -0600
    Re: Trees Nicholas Cole <nicholas.cole@gmail.com> - 2015-01-20 09:23 +0000
    Re: Trees Paul Rubin <no.email@nospam.invalid> - 2015-01-20 10:02 -0800

csiph-web