Monday, September 29, 2014

CC150 2.3 - Delete node in a singly linked list with only access to that node

For this interview question, the answer is not a common way to remove a node in  a singly linked list. Basically, you redirect the next node pointer of the previous node to the next pointer of the node you want to remove. Since you only have access to the current node, the tricky solution is you can replace current node with the next one. However, it is impossible to do that if the node is the last one of the list.
class Test2_3 {
    public static void main(String argv[]) {
        int todel = 4;
        if(argv.length > 0) {
            todel = Integer.parseInt(argv[0]);
        }
        Random rand = new Random(System.currentTimeMillis());
        // Create a list instance
        List list = new List();
        Node nodedel = null;
        for(int i = 0; i < 10; i++) {
            Node n = new Node(rand.nextInt(10));
            if(i == todel-1)  nodedel = n;
            list.attach(n);
        }
        System.out.printf("Remove %dth node of the list: ", todel);
        list.print();
        // Remove
        if(nodedel != null && nodedel.next != null) {
            Node next = nodedel.next;
            nodedel.data = next.data;
            nodedel.next = next.next;
        } else {
            System.out.println("Could not remove the last one!");
        }
        list.print();

    }
}   

Friday, September 19, 2014

Find supported image formats by matplotlib package in python

While you call matplotlib.figure.savefig, you may be wondering what type of figure I can save. You can find the answer by entering some commands in python.

By checking backend engines of pyplot
import matplotlib
['GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'MacOSX', 'QtAgg', 'Qt4Agg', 'TkAgg', 'WX', 'WXAgg', 'CocoaAgg', 'agg', 'cairo', 'emf', 'gdk', 'pdf', 'ps', 'svg', 'template']

By checking the supported file types by canvas object
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> print fig.canvas.get_supported_filetypes()
{'svgz': 'Scalable Vector Graphics', 'tiff': 'Tagged Image File Format', 'jpg': 'Joint Photographic Experts Group', 'raw': 'Raw RGBA bitmap', 'jpeg': 'Joint Photographic Experts Group', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'emf': 'Enhanced Metafile', 'svg': 'Scalable Vector Graphics', 'eps': 'Encapsulated Postscript', 'rgba': 'Raw RGBA bitmap', 'pdf': 'Portable Document Format', 'tif': 'Tagged Image File Format'}