简体   繁体   中英

Assigning recursive function to a variable in python

I'm encoding a Huffman tree in Python. I have one regular function which takes in the string to be encoded and the Huffman tree. It creates an array of the string's characters and an empty array whose entries will be the binary paths corresponding to each char. This function loops over each character in the string array, calling function 2, which recursively searches through the tree, building up the binary code and returning it once the letter has been found.

Everything is working fine - the recursive function moves through the tree properly, finding and printing the correct path. Only problem is that when I assign that return value to a variable inside function1 and append it to the binary array, it becomes None . Can you not assign a recursive return statement to a variable like that?? Any help would be greatly appreciated as I feel like I'm on the cusp of finishing this.

Here is my code:

def huffmanEncoder(s, t):
    """encodes string s with Tree t"""
    s = list(s)
    b = []
    for i in range(len(s)):
        val = recursiveHuff(t, '', s[i])
        print 'val:', val
        b.append(val)
    print b

def recursiveHuff(tree, path, char):
    """given a tree, an empty string 'path', and a character,
    finds said char in tree and returns the binary path"""
    print 'looking for:\t', char, 'path:\t', path
    if not isLeaf(tree):

        recursiveHuff(getLeftChild(tree), path+'0', char)
        recursiveHuff(getRightChild(tree), path+'1', char)
    else:
        n = getNodeValue(tree)
        if n[1] == char:
            print 'found', char, 'at', path
            return path

Your problem is that recursiveHuff doesn't return a value when you do your recursion step. You want to accumulate the path and return it. As you have it now, the changes you make to path are local to the recursive calls. (so they propagate down the chain as you descend, but not back up as you unwind)

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