在python中为变量赋值递归函数

2024-05-03 07:24:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编码Huffman树。我有一个常规函数,它接受要编码的字符串和哈夫曼树。它创建一个字符串字符数组和一个空数组,其条目将是与每个字符对应的二进制路径。这个函数循环遍历字符串数组中的每个字符,调用函数2,该函数递归地搜索树,建立二进制代码,并在找到字母后返回它。在

一切正常-递归函数在树中正确移动,找到并打印正确的路径。唯一的问题是,当我将返回值赋给function1内部的变量并将其附加到二进制数组中时,它变成None。你不能把递归返回语句赋给这样的变量吗??任何帮助都将不胜感激,因为我觉得我即将完成这一切。在

这是我的代码:

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

Tags: path函数字符串代码路径tree编码def
1条回答
网友
1楼 · 发布于 2024-05-03 07:24:31

您的问题是,当您执行递归步骤时,recursiveHuff不返回值。您需要累积路径并返回它。现在,您对path所做的更改是递归调用的本地更改。(因此,当你下降时,它们会沿着链条向下传播,但不会在你放松时向上传播)

相关问题 更多 >