Python, len function
I need some help, PLEASE LOOK AT EDIT 2 This is code of huffman:
def printHuffTree(huffTree, prefix = ''):
if len(huffTree) == 2:
print huffTree[1], prefix
exampleData = [
(0.124167 , 'e')
]
if __name__ == '__main__':
huffTree = makeHuffTree(exampleData)
printHuffTree(huffTree)
output is:
e 00
t 01
a 10
i 11
I need some function or anything which can count this nu开发者_C百科mbers; for example if
e 00
i need to count how many numbers is here: 2 (0 and 0)
so output that I need :
e 00 2
t 01 2
a 10 2
i 11 2
As I understand your question, you need to add len(prefix)
to your final print
:
def printHuffTree(huffTree, prefix = ''):
if len(huffTree) == 2:
print huffTree[1], prefix, len(prefix)
Update to answer the new question
def printHuffTree(huffTree, prefix = '', s=0):
if len(huffTree) == 2:
print huffTree[1], prefix, len(prefix)
return len(prefix)*huffTree[0]
else:
s+= printHuffTree(huffTree[1], prefix + '0')
s+= printHuffTree(huffTree[2], prefix + '1')
return s
You need to test it
For edit 2:
Using your data in exampleData
and if c
is the constant to multiply each by then:
result = sum(c*i[0] for i in exampleData)
I'm still not understanding the rest of your question.
I think you've answered your own question?! Just change print huffTree[1], prefix
to print huffTree[1], prefix, len(prefix)
.
Replace the if part of the code with
if len(huffTree) == 2:
print huffTree[1], prefix, len(prefix)
精彩评论