Mon code:Python, SUM de multiplier
import heapq
def makeHuffTree(symbolTupleList):
trees = list(symbolTupleList)
heapq.heapify(trees)
while len(trees) > 1:
childR, childL = heapq.heappop(trees), heapq.heappop(trees)
parent = (childL[0] + childR[0], childL, childR)
heapq.heappush(trees, parent)
return trees[0]
def printHuffTree(huffTree, prefix = ''):
if len(huffTree) == 2:
print huffTree[1], prefix, len(prefix) <--------------------------
else:
printHuffTree(huffTree[1], prefix + '0')
printHuffTree(huffTree[2], prefix + '1')
exampleData = [ <-------------------------------
(0.124167 , 'e'),
(0.0969225 , 't'),
(0.0820011 , 'a'),
(0.0768052 , 'i'),
(0.0368052 , 'h')
]
""" some test code
exampleData[i] = exampleData[i] + (len(prefix),)
sum(i[1]*i[0] for i in exampleData) <-this is wrong...
"""
if __name__ == '__main__':
huffTree = makeHuffTree(exampleData)
printHuffTree(huffTree)
Ma sortie est maintenant:
e 00 2
i 010 3
h 011 3
t 10 2
a 11 2
J'ai besoin:
sortie comme maintenant, mais même SUM = 2 * 0,124167 + 3 * 0,0969225 +3 * 0,0820011 + 2 * 0,0768052 + 2 * 0,0368052 ... = ?; soo dans ce cas, SUM = 1.;
premier numéro est de len (préfixe) et le second nombre est de exampleData
Toute solution?
EDIT2:
import heapq
def makeHuffTree(symbolTupleList):
trees = list(symbolTupleList)
heapq.heapify(trees)
while len(trees) > 1:
childR, childL = heapq.heappop(trees), heapq.heappop(trees)
parent = (childL[0] + childR[0], childL, childR)
heapq.heappush(trees, parent)
return trees[0]
def printHuffTree2(freqs, huffTree, prefix = ''):
if len(huffTree) == 2:
letter = huffTree[1]
val = len(prefix)*freqs[letter]
print '%s: %s\t%u * %f = %f' % \
(huffTree[1], prefix, len(prefix), freqs[letter], val)
return val
else:
lhs = printHuffTree2(freqs, huffTree[1], prefix + '0')
rhs = printHuffTree2(freqs, huffTree[2], prefix + '1')
return (lhs+rhs)
exampleData = [
(0.124167 , 'e'),
(0.0969225 , 't'),
(0.0820011 , 'a'),
(0.0768052 , 'i'),
(0.0368052 , 'h')
]
freqs = dict([(b,a) for (a,b) in exampleData])
"""
exampleData[i] = exampleData[i] + (len(prefix),)
sum(i[1]*i[0] for i in exampleData)
"""
if __name__ == '__main__':
huffTree = makeHuffTree(exampleData)
printHuffTree2(huffTree)
Ce
de me donner l'erreur
Pouvez-vous s'il vous plaît copier votre code tout, regardez EDIT2 parce que j'obtiens l'erreur,; merci beaucoup – thaking
Ajouté, s'il vous plaît voir ci-dessus. – gavinb