Math 给定一棵哈夫曼树,如何计算每个符号的哈夫曼代码?
正如标题所述,我正在编写一个函数来计算树中符号的哈夫曼代码,但我感觉完全迷失了方向 分支如下所示:Math 给定一棵哈夫曼树,如何计算每个符号的哈夫曼代码?,math,clojure,lisp,Math,Clojure,Lisp,正如标题所述,我正在编写一个函数来计算树中符号的哈夫曼代码,但我感觉完全迷失了方向 分支如下所示: {:kind :branch, :frequency frequency, :left child0, :right child1} {:kind :leaf, :frequency frequency, :value symbol} {:tree tree, :length length, :bits bits} (defn huffman-codes "Given a
{:kind :branch, :frequency frequency, :left child0, :right child1}
{:kind :leaf, :frequency frequency, :value symbol}
{:tree tree, :length length, :bits bits}
(defn huffman-codes
"Given a Huffman tree, compute the Huffman codes for each symbol in it.
Returns a map mapping each symbol to a sequence of bits (0 or 1)."
[T]
(into {} (for [s (all-symbols T)] [s (find-in-tree s T '())])
)
)
叶子看起来像这样:
{:kind :branch, :frequency frequency, :left child0, :right child1}
{:kind :leaf, :frequency frequency, :value symbol}
{:tree tree, :length length, :bits bits}
(defn huffman-codes
"Given a Huffman tree, compute the Huffman codes for each symbol in it.
Returns a map mapping each symbol to a sequence of bits (0 or 1)."
[T]
(into {} (for [s (all-symbols T)] [s (find-in-tree s T '())])
)
)
代码本身的结构如下:
{:kind :branch, :frequency frequency, :left child0, :right child1}
{:kind :leaf, :frequency frequency, :value symbol}
{:tree tree, :length length, :bits bits}
(defn huffman-codes
"Given a Huffman tree, compute the Huffman codes for each symbol in it.
Returns a map mapping each symbol to a sequence of bits (0 or 1)."
[T]
(into {} (for [s (all-symbols T)] [s (find-in-tree s T '())])
)
)
我的主要功能已经如下所示:
{:kind :branch, :frequency frequency, :left child0, :right child1}
{:kind :leaf, :frequency frequency, :value symbol}
{:tree tree, :length length, :bits bits}
(defn huffman-codes
"Given a Huffman tree, compute the Huffman codes for each symbol in it.
Returns a map mapping each symbol to a sequence of bits (0 or 1)."
[T]
(into {} (for [s (all-symbols T)] [s (find-in-tree s T '())])
)
)
所有符号返回树中所有符号的集合,我将编写一个助手函数find in tree来查找符号的位字符串
编辑:
我现在已经试过了,它让我更接近我想要的,但仍然不正确,请参见下面的错误消息
在树上找到
[s T l]
如果我离开?T
{:值tl}
在树s中合并查找:左T连接l'0
在树s中查找:右T concat l'1
错误-获取“{:c{:D0 0 0,:C0 0 1,:B0 1,:A1},:b{:D0 0,:C0 1,:B0 1,:A1},:d{:D0 0,:C0 1,:A0 1,:A1},:a{:D0 0,:C0 1,:A1}”,应为“{:D0 0,:C0 0 1,:A1}”
它获取所有正确的位字符串,但将整个映射分配给每个值,我不知道是什么错误。假设您的哈夫曼树是有效的,这意味着我们可以忽略:频率,0表示“左”,1表示“右”: defn代码映射 给定一个哈夫曼树,返回一个表示每个符号代码的映射 [{:keys[kind left-right value]}代码] 如果=种类:叶 {值代码} 合并代码映射左侧str代码0 代码映射右str代码1 演示: ;; 样本树 def根 {:种类:分支 :左{:种类:分支 :左{:种类:叶 :值X} :右{:种类:叶 :值Y} :right{:种类:叶:值Z} ;; 确保将其作为第二个参数传递 代码映射根 ;;=> {x00,y01,z1}
为了解决这个问题,您可以将arg移到一个内部帮助函数中,并且可以使递归具有TCO功能。我从您的答案中获得了一些灵感,但我的解决方案并不能完全满足我的要求。你能看看怎么了吗?