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 thecodeTable(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')