Mainly Tech projects on Python and Electronic Design Automation.

Thursday, April 02, 2009

(Ab)use of Pythons in-built data structures

I like to use Pythons in-built data structures quit a lot, and tend to force myself to ask whether I  should create my own classes, which allows you to use meaningful names for fields and add comments/docstrings to the datastructure but usually at the cost of adding more lines of text.

After writing about Huffman codes and posting solutions to Rosetta code and my blog:

 29 def codecreate(symbol2weights, tutor= False):
 30     ''' Huffman encode the given dict mapping symbols to weights '''
 31     global decode
 32 
 33     heap = [ [float(wt), [[sym, []]], repr(sym)] for sym, wt in symbol2weights.iteritems() ]
 34     heapify(heap)
 35     if tutor: print "ENCODING:", sorted(symbol2weights.iteritems())
 36     while len(heap) >1:
 37         lo = heappop(heap)
 38         hi = heappop(heap)
 39         if tutor: print "  COMBINING:", lo, '\n        AND:', hi
 40         for i in lo[1]: i[1].insert(0, '0')
 41         for i in hi[1]: i[1].insert(0, '1')
 42         lohi = [ lo[0] + hi[0] ] + [lo[1] + hi[1]]
 43         lohi.append('(%s if nextbit() else %s)' % (hi[2], lo[2]))
 44         if tutor: print "  PRODUCING:", lohi, '\n'
 45         heappush(heap, lohi)
 46     wt, codes, decoder = heappop(heap)
 47     decode = eval('lambda :' + decoder, globals())
 48     decode.__doc__ = decoder
 49     for i in codes: i[1] = ''.join(i[1])
 50     #for i in codes: i[::] = i[:2]
 51     return sorted(codes, key=lambda x: (len(x[-1]), x))
 52 

Someone posted a Java solution, that was over three times as long. Instead of just counting and comparing line counts,  I took a closer look to see what the extra code was for.

import java.util.*;

abstract class HuffmanTree implements Comparable<HuffmanTree> {
    public int frequency; // the frequency of this tree
    public HuffmanTree(int freq) { frequency = freq; }

    // compares on the frequency
    public int compareTo(HuffmanTree tree) {
        return frequency - tree.frequency;
    }
}

class HuffmanLeaf extends HuffmanTree {
    public char value; // the character this leaf represents

    public HuffmanLeaf(int freq, char val) {
        super(freq);
        value = val;
    }
}

class HuffmanNode extends HuffmanTree {
    public HuffmanTree left, right; // subtrees

    public HuffmanNode(HuffmanTree l, HuffmanTree r) {
        super(l.frequency + r.frequency);
        left = l;
        right = r;
    }
}

public class HuffmanCode {
    // input is an array of frequencies, indexed by character code
    public static HuffmanTree buildTree(int[] charFreqs) {
        PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>();
        // initially, we have a forest of leaves
        // one for each non-empty character
        for (int i = 0; i < charFreqs.length; i++)
            if (charFreqs[i] > 0)
                trees.offer(new HuffmanLeaf(charFreqs[i], (char)i));

        assert trees.size() > 0;
        // loop until there is only one tree left
        while (trees.size() > 1) {
            // two trees with least frequency
            HuffmanTree a = trees.poll();
            HuffmanTree b = trees.poll();

            // put into new node and re-insert into queue
            trees.offer(new HuffmanNode(a, b));
        }
        return trees.poll();
    }

    public static void printCodes(HuffmanTree tree, Stack<Character> prefix) {
        assert tree != null;
        if (tree instanceof HuffmanLeaf) {
            HuffmanLeaf leaf = (HuffmanLeaf)tree;

            // print out character and frequency
            System.out.print(leaf.value + "\t" + leaf.frequency + "\t");

            // print out code for this leaf, which is just the prefix
            for (char bit : prefix)
                System.out.print(bit);
            System.out.println();

        } else if (tree instanceof HuffmanNode) {
            HuffmanNode node = (HuffmanNode)tree;

            // traverse left
            prefix.push('0');
            printCodes(node.left, prefix);
            prefix.pop();

            // traverse right
            prefix.push('1');
            printCodes(node.right, prefix);
            prefix.pop();
        }
    }

    public static void main(String[] args) {
        String test = "this is an example for huffman encoding";

        // we will assume that all our characters will have
        // code less than 256, for simplicity
        int[] charFreqs = new int[256];
        // read each character and record the frequencies
        for (char c : test.toCharArray())
            charFreqs[c]++;

        // build tree
        HuffmanTree tree = buildTree(charFreqs);

        // print out results
        System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE");
        printCodes(tree, new Stack<Character>());
    }
}

I noticed that the Java was tidy, and that they had defined their own classes for a HuffmanLeaf structure used when constructing a HuffmanTree.

In my original Python, I used a nested list as the equivalent to the HuffmanLeaf of the Java example. It worked, but I had to introduce 'magic constants' to access the fields of the Python leaf , which is also un-named as a structure in the program (lline 33 of the Python code creates a list of Leaf structures):

33  heap = [ [float(wt), [sym, []]] for sym, wt in symbol2weights.iteritems() ]

Now I didn't want to go to the trouble of creating my own classes, but that's were the new namedtuple class factory of Python 2.6 came to the rescue.

namedtuple

namedtuple will generate a subtype of the tuple class that allows the fields of the tuple to be named and accessed via subscription, [], or as if the fields are instance variable names.

I modified my Python program to use two named tuples:

  1. For the Leaf structure as a whole in line 3.
  2. For a component of the Leaf structure that holds the symbol and the Huffman code (accumulated so far), in line 4.
 1 from collections import namedtuple
 2 
 3 Leaf = namedtuple('Leaf', 'weight, symbols')
 4 SH = namedtuple('SH', 'sym, huff')
 5 
 6 def codecreate2(symbol2weights, tutor= False):
 7     ''' Huffman codecreate2 the given dict mapping symbols to weights '''
 8     heap = [ Leaf(weight=float(wt), symbols=[ SH(sym, []) ])
 9              for sym, wt in symbol2weights.iteritems() ]
10     heapify(heap)
11     if tutor: print "ENCODING:", sorted(symbol2weights.iteritems())
12     while len(heap) >1:
13         lo = heappop(heap)
14         hi = heappop(heap)
15         if tutor: print "  COMBINING:", lo, '\n        AND:', hi
16         for sh in lo.symbols: sh.huff.insert(0, '0')
17         for sh in hi.symbols: sh.huff.insert(0, '1')
18         lohi = Leaf(weight  = lo.weight + hi.weight,
19                     symbols = lo.symbols + hi.symbols)
20         if tutor: print "  PRODUCING:", lohi, '\n'
21         heappush(heap, lohi)
22     symbols = heappop(heap).symbols
23     symbols = [SH(sym, ''.join(huff)) for sym, huff in symbols]
24     return sorted(symbols, key=lambda sh: (len(sh.huff), sh))
25 

The class generation is succinct in lines 3 and 4, and I use the field names for clarity for example when creating the original list of Leaves that will form the heap in line 8

Printing namedtuples

The print statements stay the same, but before you got output like this:

...

  COMBINING: [2.5, ['C', []]] 
        AND: [5.0, ['A', []]]

PRODUCING: [7.5, ['C', ['0']], ['A', ['1']]] 

...

Now you get the clearer:

ENCODING:
[('A', '5'), ('B', '25'), ('C', '2.5'), ('D', '12.5')]

  COMBINING: Leaf(weight=2.5, symbols=[SH(sym='C', huff=[])]) 
        AND: Leaf(weight=5.0, symbols=[SH(sym='A', huff=[])])

  PRODUCING: Leaf(weight=7.5, symbols=[SH(sym='C',
huff=['0']), SH(sym='A', huff=['1'])]) 

  COMBINING: Leaf(weight=7.5, symbols=[SH(sym='C',
huff=['0']), SH(sym='A', huff=['1'])]) 
        AND: Leaf(weight=12.5, symbols=[SH(sym='D', huff=[])])

PRODUCING: Leaf(weight=20.0, symbols=[SH(sym='C', huff=['0', '0']),
SH(sym='A', huff=['0', '1']), SH(sym='D', huff=['1'])]) 

COMBINING: Leaf(weight=20.0, symbols=[SH(sym='C', huff=['0', '0']),
SH(sym='A', huff=['0', '1']), SH(sym='D', huff=['1'])]) 
        AND: Leaf(weight=25.0, symbols=[SH(sym='B', huff=[])])

PRODUCING: Leaf(weight=45.0, symbols=[SH(sym='C', huff=['0', '0',
'0']), SH(sym='A', huff=['0', '0', '1']), SH(sym='D', huff=['0', '1']),
SH(sym='B', huff=['1'])])

Conclusion

 Although you can do so much with Python lists, if each position in the list has a fixed meaning then you might be best to use tuples, and if you should be using tuples, then namedtuples can make your code more readable without bloating it with long class definitions.

- Paddy.

6 comments:

  1. Please can you fix your html?!

    ReplyDelete
  2. Hi
    Have you implemented the decoder as well?

    ReplyDelete
  3. Hi. Some HTML problems made your post completely unreadable.

    ReplyDelete
    Replies
    1. Yep. That's an issue with blogger and I haven't got around to reposting it. It was fine when posted, and I am aware. Thanks for your concern.

      Delete
    2. are you still aware? it is really hard to read :(

      Delete
  4. HTML fixed. Please note that the code on rosettacode.org may have been updated over the years.

    ReplyDelete

Followers

Subscribe Now: google

Add to Google Reader or Homepage

Go deh too!

whos.amung.us

Blog Archive