我正在尝试实现霍夫曼编码算法。
我写了以下代码
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'
我不知道如何解决这个错误。有人可以帮我吗 ?
谢谢