简体   繁体   中英

Passing Trie tree node as parameter - not working

I'm trying to implement a function that reads all words contained in a Trie tree, stores them in a list with their keys and writes them in a .csv file. The function 'insertTrie' works fine; however, when I pass 'root' as an argument to the function 'getAllTrie', for some reason it adds a string ('q') to the node when I print it within the function (as a test) and then the "AttributeError: 'str' object has no attribute 'char'" happens. When I print 'root' outside the function, the string is not there. What is causing this? I've spent a long time trying to find the answer.

import csv

class Node():
   def __init__(self):
       self.sons = {}
       self.char = None
       self.value = None

def insertTrie(currentNode, word, size):
    if(size == len(word)):
        if(currentNode.value is None):
        currentNode.value = 1
        else:
            currentNode.value += 1
        return currentNode
    currentChar = word[size]
    if(currentChar not in currentNode.sons):
        currentNode.sons[currentChar] = Node()
        currentNode.sons[currentChar].char = currentChar
    currentNode.sons[currentChar] = insertTrie(currentNode.sons[ccurrentChar], word, size+1)
    return currentNode

def getAllTrie(currentNode, findWord):
    if(currentNode is not None):
        #print(currentNode) -> print root inside function, 'q' appears
        if(currentNode.char is not None):
            if(findWord is None):
                findWord = []
            findWord.append(currentNode.char)
        if(currentNode.value is not None):
            wordAndKey = [''.join(findWord), currentNode.value]
            writeCSVfile('exit.csv', wordAndKey)    # writes word and key in csv file
            findWord = None
        for son in currentNode.sons:
            getAllTrie(son, findWord)

root = Node()
testStr = 'querida queremos ate quero quero'
listStr = testStr.split( )
for word in listStr:
    root = insertTrie(root, word, 0)

#print(root) -> print root outside of function, 'q' doesn't appear
getAllTrie(root, None)

When I print the 'root' outside the function 'getAllTrie' (in commentary in the code), it prints this:

<__main__.Node object at 0x03323610>

But when I print it inside the function (also in commentary), it prints this:

<__main__.Node object at 0x03323610>
q

I have no idea why that 'q' is there. It's the character contained in one of the root's sons, but it shows when I print the root itself in the function, and I have no idea why.

Your sons attribute is a dict, mapping single-character strings to nodes.

So, when you do this:

for son in currentNode.sons:

… each son is a single-character str object, not a Node object. That's why the first recursive call prints out q , and why it raises an exception about that 'q' string not having a sons attribute.

If you want to iterate over the values in a dict, rather than the keys , you need to say so:

for son in currentNode.sons.values():

You have multiple other errors in your code, from invalid indentation to typos like ccurrentChar , and it's incomplete (there's no writeCSVFile function anywhere), so I can't test whether this actually fixes your function—but it does fix this particular bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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