import sys
class Huffman:#最优二叉树
def __init__(self, wwl):
self.wwl = []
m = len(wwl)
for i in sorted(wwl):#权排序
self.wwl.append(Node(i))
for i in self.wwl[:m-1]:
m1 = m2 = sys.maxsize
x1 = x2 = None
for j in self.wwl[self.wwl.index(i):]:
if j.ww<m1 and j.parent is None:
m2 = m1
x2 = x1
m1 = j.ww
x1 = j#最小权
elif j.ww<m2 and j.parent is None:
m2 = j.ww
x2 = j#次小权
self.wwl.append(Node(m1+m2))
x1.parent = self.wwl[-1]
x2.parent = self.wwl[-1]
self.wwl[-1].left = x1
self.wwl[-1].right = x2
self.root = self.wwl[2*m-2]
class Node:
def __init__(self, ww):
self.ww = ww
self.left = None
self.right = None
self.parent = None
w = [2,3,5,7,11,13,17,19,23,29,31,37,41]
h=Huffman(w)
for i in range((len(h.wwl)+2)//2):
j = h.wwl[i]
ans = ''
while j.parent:
ans = '0'+ans if j == j.parent.left else '1'+ans
j = j.parent
print("编码",h.wwl[i].ww,ans)
编码 2 1011110
编码 3 1011111
编码 5 101110
编码 7 10110
编码 11 0100
编码 13 0101
编码 17 1010
编码 19 000
编码 23 001
编码 29 011
编码 31 100
编码 37 110
编码 41 111