#! /usr/bin/python from Numeric import * # David MacKay Dec 2005 # huffmano.p - octave friendly version of huffman.p # # - writes a huffman code # # usage: # $ huffman.py < probs > codewords1 # # input: to standard input, or in a file, should be something like this: # # a 10 # b 7 # c 3 # d 2 # # or # # # Comment lines are allowed # X 0.3 # Y 0.4 # Z 0.3 # # The corresponding output will be the codewords: # # a 0 # b 10 # c 110 # d 111 # # # the start. # class node: def __init__(self, count, index): self.count = count self.index = index def __cmp__(self, other): return cmp(self.count, other.count) ## recursive function def iterate (c , m) : ## c is the list of values and associated numbers; m is the number of ## iterations remaining. # this is not the most elegant huffman algorithm! # run through the array, finding the smallest two entries ## this makes c be an increasing list. c.sort() th = c[ 1 ].count first = c[0].index second = c[1].index bot = c[ 0 ].count c[1].count += bot del c[0] # record what has been done print "combining",first,second for v in c : print v.count,v.index if ( m > 2 ) : iterate ( c , m-1 ) ## that's all for iterate counts = [ 10, 5, 2, 3 ] c=[] m=0 for co in counts : m += 1 c.append( node( co, m ) ) ## c = [ node( 10 , 1 ) , node( 5 , 2 ) , node( 2 , 3 ) , node( 3 , 4 ) ] c.sort() ## main program starts here M = len(c) print M if (M <= 1): print "too few symbols\n" exit(0) # # make huffman code # iterate ( c , M ) # ff and ss now contain lists of branching instructions # now deduce the codewords. Start from the root with the null codeword. #$codes[0] = "" ; #$lengths[0] = 0 ; #for ( $mm = 2 ; $mm <= $M ; $mm ++ ) { # $f = $ff[$mm] ; # $s = $ss[$mm] ; # $co = $codes[$f] ; # this is the one we will expand # $le = $lengths[$f] ; # # move down everyone below s # for ( $m = $mm - 1 ; $m > $s ; $m -- ) { # $codes[$m] = $codes[$m-1] ; # $lengths[$m] = $lengths[$m-1] ; # } # $codes[$f] = $co."0" ; # $codes[$s] = $co."1" ; # $lengths[$f] = $le + 1 ; # $lengths[$s] = $le + 1 ; # write the answer # end