[英]Assigning recursive function to a variable in python
我正在用Python编码霍夫曼树。 我有一个常规函数,它接受要编码的字符串和霍夫曼树。 它创建一个由字符串字符组成的数组和一个空数组,其条目将是与每个字符对应的二进制路径。 该函数遍历字符串数组中的每个字符,并调用函数2,该函数递归地搜索树,构建二进制代码,并在找到字母后将其返回。
一切工作正常-递归函数正确地在树中移动,找到并打印正确的路径。 唯一的问题是,当我将该返回值分配给function1内部的变量并将其附加到二进制数组时,它变为None
。 您不能为这样的变量分配递归return语句吗? 任何帮助将不胜感激,因为我觉得自己快要完成了。
这是我的代码:
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
您的问题是执行递归步骤时recursiveHuff不会返回值。 您要累积路径并返回它。 现在,您对路径所做的更改在递归调用中是本地的。 (因此它们在您下降时沿着链条传播,但在您放松时不会备份)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.