哈夫曼編碼的python實現

2021-10-07 23:25:33 字數 1846 閱讀 8309

哈夫曼編碼的實現在哈夫曼樹的是線上新增了leftname和rightname的字段,以及編碼字段。同樣,學習哈夫曼編碼的部落格也是非常有趣的漫畫部落格:

# definition for a binary tree node.

class treenode:

def __init__(self, x, y):

self.val = x

self.left = none

self.right = none

self.name = y

class solution:

def huffmantree(self, weights, forest):

while len(weights) > 1:

tree = treenode(none, none)

tree.left = forest[0]

tree.right = forest[1]

tree.val = weights[0] + weights[1]

weights.pop(0)

weights.pop(0)

forest.pop(0)

forest.pop(0)

fathernode = tree.val

for i in range(0, len(weights)):

if fathernode <= weights[i]:

weights = weights[:i] + [fathernode] + weights[i:]

forest = forest[:i] + [tree] + forest[i:]

break

elif i == len(weights) - 1 and fathernode > weights[i]:

weights = weights + [fathernode]

forest = forest + [tree]

return tree

def get_huffman_code(self, tree, code, codes):

if not tree:

return codes

if tree.name:

codes[tree.name] = code

left = code + '0'

right = code + '1'

self.get_huffman_code(tree.left, left, codes)

self.get_huffman_code(tree.right, right, codes)

else:

left = code + '0'

right = code + '1'

self.get_huffman_code(tree.left, left, codes)

self.get_huffman_code(tree.right, right, codes)

return codes

if __name__ == '__main__':

weights = [2, 3, 7, 9, 18, 25]

chars = ['a', 'b', 'c', 'd', 'e', 'f']

forest =

for i in range(0, len(weights)):

s = solution()

tree = s.huffmantree(weights, forest)

result = s.get_huffman_code(tree, '', {})

for k, v in result.items():

print(k + '=' + v)

Python 實現哈夫曼樹和哈夫曼編碼

技術部落格 下面主要來看一下哈夫曼樹的 python 實現 usr bin env python coding utf 8 統計字元出現頻率,生成對映表 defcount frequency text chars ret for char in text if char in chars conti...

哈夫曼樹與哈夫曼編碼的實現 python

建立節點類,用於每個節點的生成 class hfmnode def init self self.name none self.weight none self.leftchild none self.rightchild none self.parent none 構建哈夫曼樹 def creat...

哈夫曼編碼實現

define huffmancode char typedef struct node huffmantree struct node 葉節點為n的哈夫曼樹有2 n 1個節點 用 1表示當前parent未被訪問 huffmantree createhuffmantree int wet,int n ...