Hướng dẫn list to tree python

Me and my friend are working on a simple Python project. Actually we are implementing the prefix parallel sum algorithm in our own way.

Nội dung chính

  • How do you make a list tree in Python?
  • How do I turn a tree into a list?
  • How do you convert a list in Python?
  • How do you create a binary search tree from a list of numbers in Python?

We are creating and processing a binary tree with a really weird format. We would like to convert this format to one that is accepted by Tree printing libraries/software like ete2.

So, every level of the tree is pushed in a list in that way

[ [level0], [level1], ... [level i-1], [root] ]

In our format every internal list (tree's level) has even number of nodes or leaves.

For instance, say we have this input: [1, 2, 3, 4, 5]. This will produce the following output list: [[1, 2, 3, 4], [3, 7], [10, 5], [15]]

The issue with the above output example is that sometimes leaves are not on the last level, but they are included in upper level lists. This makes it hard to process the list of lists and distinguish nodes from leaves and also arrange them in the correct position.

We would like to visualize this as follows:

http://i.imgur.com/BKrqNZi.png

where numbers included in parenthesis are nodes and the other ones leaves.

In order to produce this output tree, we would like to use one Tree drawing library. Most of them expect this type of format: [root, [left], [right]]

So, in our example our format should be something like this:

[15, [10, [3, [1], [2]], [7, [3], [4]] ], [5] ]

Because we are not in a position at the moment to rewrite the whole logic of our code, we are looking for a smart way convert our weird format into that one.

Any ideas are welcome. Thank you very much in advance.

Given a list of lists, write a Python program to convert the given list of lists into a tree-like dictionary.

Examples:

Input : [[1], [2, 1], [3, 1], [4, 2, 1], [5, 2, 1], [6, 3, 1], [7, 3, 1]]
Output : {1: {2: {4: {}, 5: {}}, 3: {6: {}, 7: {}}}}

Input : [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]
Output : {'A': {'C': {'D': {}}, 'B': {}}}

 
Method #1 : Naive Method
This is a Naive approach in which we use two for loops to traverse the list of lists. We initialize the empty dictionary ‘tree’ to currTree and each time we check if the key (list of list’s item) is included in the currTree or not. If not, include it in the currTree, otherwise do nothing. Finally, assign the currTree[key] to currTree.

def formTree(list):

    tree = {}

    for item in list:

        currTree = tree

        for key in item[::-1]:

            if key not in currTree:

                currTree[key] = {}

            currTree = currTree[key]

    return tree

lst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]

print(formTree(lst))

Output:

{'A': {'B': {}, 'C': {'D': {}}}}

 
Method #2 : Using reduce()
The reduce() function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. We will use reduce() to traverse the dictionary and reuse getTree() to find the location to store the value for setTree(). All but the last element in mapList is needed to find the ‘parent’ dictionary to add the value to, then use the last element to set the value to the right key.

from functools import reduce

from operator import getitem

def getTree(tree, mappings):

    return reduce(getitem, mappings, tree)

def setTree(tree, mappings):

    getTree(tree, mappings[:-1])[mappings[-1]] = dict()

lst = [['A'], ['B', 'A'], ['C', 'A'], ['D', 'C', 'A']]

tree ={}

for item in lst:

    setTree(tree, item[::-1])

print(tree)

Output:

{'A': {'B': {}, 'C': {'D': {}}}}

How do you make a list tree in Python?

To create a tree in Python, we first have to start by creating a Node class that will represent a single node. This Node class will contain 3 variables; the first is the left pointing to the left child, the second variable data containing the value for that node, and the right variable pointing to the right child.

How do I turn a tree into a list?

In this article we will see the two approaches to convert a nested list into to add dictionary whose elements represent a tree like data structure..

Using Slicing. We reverse the items in the list aby slicing and then check if the item is present in the list. ... .

Example. ... .

Output. ... .

Using reduce and getitem. ... .

Example. ... .

Output..

How do you convert a list in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do you create a binary search tree from a list of numbers in Python?

First you can implement your BinaryTree. printTree() function as _Node. printTree() . You can't do a straight copy and paste, but the logic of the function won't have to change much.