简体   繁体   English

如何在 python 中以树形结构打印 Trie?

[英]How to print Trie in tree structure in python?

I am still a beginner for programming.我仍然是编程的初学者。 I do not know how to print trie in tree structure as I have try for a few methods.我不知道如何在树结构中打印 trie,因为我尝试了几种方法。 Anyone can help?任何人都可以帮忙吗?

class TrieNode:
 
    def __init__(self, data):
 
        self.data = data
        self.is_end = False
        self.children = {}
 
class Trie(object):
 
    def __init__(self):
        self.root = TrieNode("")

    def insert(self, array):
        node = self.root
 
        for x in array:
            if x in node.children:
                node = node.children[x]
                print(node.data)
            else:
                new_node = TrieNode(x)
                node.children[x] = new_node
                node = new_node
                print(node.data)
        node.is_end = True

Below is the code from the main class:-以下是主要 class 的代码:-

tr = Trie()
n = int(input("Enter number of file(s): "))
for x in range (n):
    path = input("Enter your directory path: ")
    tr.insert(path.split("/"))
print(tr.root.data)

You could define a __repr__ method on your Trie class so that when you do print(tr) , that method will be called, and you'll get the tree printed in the way you want.您可以在Trie class 上定义一个__repr__方法,这样当您执行print(tr)时,该方法将被调用,并且您将以所需的方式打印树。

Here is possible implementation for such a __repr__ method: it uses a recursive function and an indent variable that will ensure that items are indented:这是这种__repr__方法的可能实现:它使用递归 function 和一个indent变量,以确保项目缩进:

    def __repr__(self):
        def recur(node, indent):
            return "".join(indent + key + ("$" if child.is_end else "") 
                                  + recur(child, indent + "  ") 
                for key, child in node.children.items())

        return recur(self.root, "\n")

This string representation will append a $ after each data when the corresponding is_end attribute is True.这个字符串表示将 append 每条数据后一个$当对应的is_end属性为 True 时。

A remark about your trie implementation:关于您的 trie 实现的评论:

You are currently storing the data twice: once as a data attribute, and a second time as a key in the children dictionary.您当前存储数据两次:一次作为data属性,第二次作为children字典中的键。 This should not be necessary.这不应该是必要的。 At the two places where you use node.data , you could use x instead -- they have the same value.在您使用node.data的两个地方,您可以使用x代替——它们具有相同的值。

You can then remove the data attribute from your TrieNode class.然后,您可以从TrieNode class 中删除data属性。 The code will then look like this:代码将如下所示:

class TrieNode:
    def __init__(self):
        self.is_end = False
        self.children = {}


class Trie(object):
    def __init__(self):
        self.root = TrieNode()

    def insert(self, array):
        node = self.root
 
        for x in array:
            if x in node.children:
                node = node.children[x]
            else:
                child = TrieNode()
                node.children[x] = child
                node = child
            print(x)
        node.is_end = True

    def __repr__(self):
        def recur(node, indent):
            return "".join(indent + key + ("$" if child.is_end else "") 
                                  + recur(child, indent + "  ") 
                for key, child in node.children.items())

        return recur(self.root, "\n")


# Main code
tr = Trie()
n = int(input("Enter number of file(s): "))
for x in range (n):
    path = input("Enter your directory path: ")
    tr.insert(path.split("/"))
print(tr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM