dimanche 28 juin 2020

How would I create a function to test my Tree before an algorithm runs?

For the following code below, I am looking for some sort of way to add testing data. How would I go about creating a function to check that the Huffman Tree is checked and confirmed as working before the algorithm executes? Thanks in advance for any help!

#Huffman Coding Algorithm

string = input("Please Enter a Phrase Consister of Letters and or Spaces: " + "\n")
print("")


#Creating the tree nodes
class HuffmanTree(object):
    
    def __init__(self, left = None, right = None):
        self.left = left
        self.right = right
    
    def child(self):
        return(self.left, self.right)
    
    def nodes(self):
        return (self.left, self.right)

    def __str__(self):
        return "%s_%s" % (self.left, self.right)

#Main function for Huffman coding. 
def Huffman_Compression(node, left = True, binString = ""):
    if type(node) is str:
        return {node: binString}
    (left, right) = node.child()
    dt = dict()
    dt.update(Huffman_Compression(left, True, binString + "0"))
    dt.update(Huffman_Compression(right, False, binString + "1"))
    return dt

#Calculating the frequency of characters 
freq = {}
for c in string:
    if c in freq:
        freq[c] += 1
    else:
        freq[c] = 1
        
freq = sorted(freq.items(), key = lambda x: x[1], reverse = True)

nodes = freq

while len(nodes) > 1:
    (key1, c1) = nodes[-1]
    (key2, c2) = nodes[-2]
    nodes = nodes[:-2]
    node = HuffmanTree(key1, key2)
    nodes.append((node, c1 + c2))
    
    nodes = sorted(nodes, key = lambda x: x[1], reverse = True)
    
huffmancoding = Huffman_Compression(nodes[0][0])

print(" Characters | Huffman Output ")
print("-------------------------------")

for (char, frequency) in freq:
    print(" %-4r |%12s" % (char, huffmancoding[char]))

Aucun commentaire:

Enregistrer un commentaire