Skip to content
Advertisement

how to build a tree for ordered numbers?

I am trying build a tree (dictionary ) from input numbers. My main criteria for the tree is all the nodes in a level are in a same range. ( a series of data from parent) I think you will get idea from my examples-

Please see the example

JavaScript

I tried to build a tree initially. This will work only for the data 1-9, anybody help me to find a better solution This is how I tried

JavaScript

Advertisement

Answer

Here’s an attempt:

Imports: I’m working with defaultdict and groupby, both from the standard library:

JavaScript

Two helper functions for later:

JavaScript

Step 1: Establishing the levels (the assumption is that input_list is sorted):

JavaScript

The result looks like:

JavaScript

Step 2: Finding the parent child relationships:

JavaScript

Output:

JavaScript

I’m sure there are plenty of wrinkles in it …

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement