简体   繁体   中英

I am struggling to build a Huffman tree from the leaves up. I have my sorted list, but don't know how to proceed

So this function takes a string, and I do the following code to get it to create a list of tuples [character, frequency]. We aren't using proability, just actual frequency. Any suggestions to get me started on building the correct tree in a way that I can traverse it back down to add its 1s and 0s?

from operator import itemgetter, attrgetter, methodcaller
def code(msg):
# list of characters already counted
characters = []
# list of tuples
frequencies = []
# look through the message
for char in msg:
    if char not in characters:
        print(char)

        characters.append(char)
        thisCount = 0
        # if current character has already been added to list
        for chara in msg:
            if char == chara:
                # increase its count if another found
                thisCount = thisCount + 1
        # create its tuple
        tup = (char, thisCount)
        # add tuple to frequencies
        frequencies.append(tup)

# sort tuple list by element[1] numerically
sortedFreq = sorted(frequencies, key=lambda x: x[1])
print(sortedFreq)
make_Tree(sortedFreq)
return

First and foremost, get comfortable with the Python structures that handle this application. A basic dictionary will do this much better than your pair of arrays, and a Counter will do this in short order:

from collections import Counter
freq = Counter(msg)

freq is now a dictionary in the form

{'l': 2, 'h': 1, 'e': 1, 'o': 1}

representing the message "hello". Now, to get a sorted list of tuples, just grab the tuples from the Counter and plug that into your sort:

sortedFreq = sorted(freq.items(), key=lambda x: x[1])

Now for the construction. I don't know what data structure you've set up, but the algorithm is basically this:

while len(sortedFreq) > 1
    join the last two elements
    re-sort the tree

Does this get you moving toward a solution?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM