Question

from arrayheap import ArrayHeap
    def generateTable(self, node, table):
        def codeTable(node, codeString):
            if node.isLeaf:
                table[node._char] = codeString
                return
            if node.getleft() is not None:
                table(node.getLeft(), codeString + '0')
            if node.getRight() is not None:
                table(node.getRight(), codeString + '1')
        codeTable(node, '')
        return(table)

def main():
    with open('codetable.txt', 'w') as cdt:
        codeTable = {}
        codeTable = HTree.generateTable(HTree, codeTable)
        for i in sorted(codeTable):
            cdt.write(str(i) + '\t' + str(codeTable[i]) + '\n')
main()

I am trying to output to a file the binary traversal to each individual node in a tree. I have left the preorder and postorder traversal methods in the file for reference. My question is what is wrong with my generateTable() method (most of the code was provided to me) I would like to output it so that it lists the traversal, 0 being left 1 being right, in the format <ascii value> : <binary path>. The thing is, when I run this code, my output file codetable.txt is empty. What am I doing wrong?

Was it helpful?

Solution

generateTable() returns table unchanged; you passed in an empty dictionary, and the function does nothing else but return that same object.

The nested codeTable() function is not used; nothing ever actually calls it. Even if you unindented the codeTable(node, '') call to be outside of the nested function, that function has several flaws:

  • codeTable() only takes one argument, but the codeTable(node, '') call passes in two arguments.
  • It only ever references node.isLeaf but does not call it.
  • It treats table as both a dictionary and a callable.

I suspect you were meant to call it recursively; something like the following perhaps?

def generateTable(self, node, table):
    def codeTable(node, codeString):
        if node.isLeaf():
            table[node._char] = codeString
            return
        if node.getleft() is not None:
            codeTable(node.getLeft(), codeString + '0')
        if node.getRight() is not None:
            codeTable(node.getRight(), codeString + '1')
    codeTable(node, '')
    return(table)

This now generates a mapping with paths to leaf nodes, keyed by the value of the leafnode; the path consists of 0 and 1 characters denoting left and right nodes on the tree.

Once the table has been generated, the writing to a file can be simplified to:

for i in sorted(codeTable):
    cdt.write(str(i) + '\t' + str(codeTable[i]) + '\n')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top