霍夫曼代码树练习,使用以下菜单选项编写程序:
询问用户文本文件的名称,然后读取文件,计算128个ascii字符的相对频率,并将其写入文本文件,每行一个浮点频率。
读取包含128行的文本文件,每行包含一个浮点数,该浮点数表示给定文本类型中相应ascii符号的相对频率。每行对应于该行号的ASCII码,因此第32行等于ASCII码32。
使用文件中的Assigned Frequencies构建一个Huffman Code树,忽略小于32的ascii代码,即只使用第32-127行。
使用以下算法打印树:
def printTree("Tree", indent = ""):
#inorder Traversal
if theres a right subtree:
printTree("node.right",indent+" ")
print(indent, data)#data is equal to a character and if no char, then is equal to a " * "
if theres a left subtree:
printTree("node.left",indent+" ")
这就是我正在尝试做的事情,但是我已经能够建造一棵树(至少我认为我已经能够了,但是我无法穿越树的左或右儿童而且为代码表构建相应的字节代码。我已经做到了这一点,但现在我已经迷失了,我需要一些外部输入来帮助我找到正确的方向,并提出问题或有人报告我的内容做错了,帮我告诉我我错了。
def pushDown(H,i,n):
#Allows larger values to be at top of tree
while i <= n//2:
lc = i*2
rc = 2*i+1
if H[lc] > H[i] and (lc == n or H[lc] >= H[rc]):
H[i],H[lc] = H[lc],H[i]
i = lc
elif rc <= n and H[i] < H[rc]:
H[i],H[rc] = H[rc],H[i]
i = rc
else:
break
def Heapify(H):
#Creates a tree
n = len(H)-1
for i in range(n//2,0,-1):
pushDown(H,i,n)
return H
def Hsort(H):
#Sort into a heap
Heapify(H)
n = len(H)-1
while n > 1:
H[n], H[1] = H[1], H[n]
n = n-1
pushDown(H,1,n)
return H
def heapify(array, n, i):
highest = i
l = (2 * i) + 1
r = (2 * i) + 2
if l < n and array[i] < array[l]:
highest = l
if r < n and array[highest] < array[r]:
highest = r
if highest != i:
array[i],array[highest] = array[highest],array[i]
heapify(array, n, highest)
return array
def Hsort(array):
n = len(array)
while n > 1:
for i in range(n, -1, -1):
heapify(array,n, i)
for j in range(n-1, 0, -1):
array[j], array[0] = array[0], array[j]
heapify(array, j, 0)
n -= 1
return array
def hf(dic):
d = [dic]
d2 = []
node = []
left = []
right =[]
length = len(dic)
lbits = {}
rbits = {}
for key, value in d[0].items():
d2.append(value)
for i in range(length):
r = min(d2)
node.append(r)
d2.remove(r)
while len(node) > 1:
Node = node[0] + node[1]
child = Hsort(list((node[0],node[1])))
if node[0]:
left.append(child[0])
if node[1]:
right.append(child[1])
node.remove(node[0])
node.remove(node[0])
node.append(Node)
for l in left:
lbits[l] = 0
for r in right:
rbits[r] = 1
print('lbits', lbits, '\nrbits', rbits)
def path(dic = None):
if dic in [None, '']:
print('No root, Error')
raise KeyError
else:
hf(dic)
path()
##
##Input requires to loading from a file
##but Here are some frequencies that are in one of my test files.
0.05926
0.01025
0.01232
0.0336
0.09376
0.01824
0.01116
0.06372
0.04097
0.00055
0.00529
0.02724
0.01829
0.05085
0.05385
0.0093
0.00021
0.03707
0.04275
0.07018
0.01959
0.0071
0.01418
0.0006
0.01303
0.00082
如果格式不正确,我会提前对不起,我对这个程序感到很累和沮丧。