霍夫曼编码错误

时间:2013-04-25 07:12:07

标签: python huffman-code

我正在尝试实现霍夫曼编码算法。

我写了以下代码

def make_leaf(symbol,weight):
    return (symbol,weight)

def is_leaf(x):
    return isinstance(x,tuple) and \
           len(x)==2 and \
           isinstance(x[0],str) and \
           isinstance(x[1],int)

def get_leaf_symbol(leaf):
    return leaf[0]

def get_leaf_freq(leaf):
    return leaf[1]

def get_left_branch(huff_tree):
    return huff_tree[0]

def get_right_branch(huff_tree):
    return huff_tree[1]


def get_symbols(huff_tree):
    if is_leaf(huff_tree):
        return [get_leaf_symbol(huff_tree)]
    else:
        return huff_tree[2]

def get_freq(huff_tree):
    if is_leaf(huff_tree):
        return get_leaf_freq(huff_tree)
    else:
        huff_tree[3]


def make_huffman_tree(left_branch,right_branch):
    return [left_branch,
            right_branch,
            get_symbols(left_branch) + get_symbols(right_branch),
            get_freq(left_branch) + get_freq(right_branch)]

但是当我尝试通过编写以下代码来构建二叉树时

ht01 = make_huffman_tree(make_leaf('A', 4),
                        make_huffman_tree(make_leaf('B',2),
                                          make_huffman_tree(make_leaf('D', 1),
                                                         make_leaf('C', 1))))

我收到这样的错误:

Traceback (most recent call last):
  File "C:\Users\Swadesh\Documents\Anmol\Python\huffman trial.py", line 47, in <module>
    make_leaf('C', 1))))
  File "C:\Users\Swadesh\Documents\Anmol\Python\huffman trial.py", line 41, in make_huffman_tree
    get_freq(left_branch) + get_freq(right_branch)]
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

我不知道如何解决此错误。有人可以帮我吗 ?

由于

1 个答案:

答案 0 :(得分:3)

你错过了get_freq()函数最后一行的'return'。

如果您没有从函数返回任何内容,Python将使用None作为返回值。

当您尝试在添加中使用此返回值时,您会收到您发布的错误(不能将None添加到整数)。

相关问题