{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Together with friends, I participated in the Google Hashcode in 2015. It was a lot of fun, and we made it to the final round at the Google Paris offices, finishing 49th out of 65 teams (our qualification scores were better: 20th out of 230 teams). To get an idea of what it was like, you can read write-ups from a fellow competitor and 2014 winner, Antoine Amarilli, for the [2014 final round](https://a3nm.net/blog/google_hashcode_2014_fr.html), the [2015 qualification round](https://a3nm.net/blog/hashcode_2015_selection.html) and [the 2015 final round](https://a3nm.net/blog/google_hashcode_2015.html). Preparing for this year's Hashcode, I want to revisit some thoughts about the competition and present some tips for mastering it in this blog post." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The tasks " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Based on the previous editions, I believe this year's Hashcode will again be about solving an optimization problem. Last year's problems were:\n", "\n", "- facade painting (training)\n", "- data center server placement (qualification)\n", "- pizza slicing (warm-up final round)\n", "- Google Loon trajectory optimization (final round)\n", "\n", "This year's training problem is a variation on the facade painting problem. \n", "\n", "What all these problems have in common is that they are optimization problems:\n", "\n", "- facade painting: compute minimum set of painting instructions to recover the required picture\n", "- data center: assign servers to rows and then groups to servers so as to maximize the remaing power of the smallest group in the case of an outage\n", "- pizza slicing: make the biggest number of slices possible given a set of constraints\n", "- Loon: find the best trajectories to maximize the coverage in time of the balloons\n", "\n", "Another observation is that the problems are non-trivial in every case: optimization of an object that is not easily manipulated (painting instructions, rows of servers, pizza slices, ballons). This leads me to what I believe is a key point in this competition: **modeling**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Modeling problems " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All of these problems are described in text form. To the human brain, concepts are easily picked up from their description and manipulated. The important point is how these abstract concepts are translated when putting the code to practice.\n", "My previous participations have led me to believe that the challenge is often not one of performance and score, but rather one of translating an idea of an approximate solution to code in a finite amount of time. \n", "\n", "Thus my current vision is: code clarity is better than code performance, even in this sort of contest. It is better to have a slow solution that produces a result rather than a fast solution that doesn't produce a result due to various reasons (in my experience because the code is too complex to finish it). " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Norvig's approach to modeling (points)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The approach I advocate is essentially what [Peter Norvig does when he codes](http://norvig.com/ipython/README.html). Peter Norvig has a very clean approach to doing things. Usually, he first defines the objects he will deal with. Good examples of this can be found in the [Convex Hull notebook](http://nbviewer.jupyter.org/url/norvig.com/ipython/Convex%20Hull.ipynb), where he defines the following:\n", "\n", "> - Point: We'll define a class such that Point(3, 4) is a point where p.x is 3 and p.y is 4.\n", "> - Set of Points: We'll use a Python set: {Point(0,0), Point(3,4), ...}\n", "> - Polygon: We'll represent a polygon as an ordered list of vertex points.\n", "\n", "As noted by Peter, several implementations are possible for 2d points. He uses several, depending on the problem. \n", "\n", "Using `namedtuples` in Python:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import collections\n", "\n", "Point = collections.namedtuple('Point', 'x, y')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This easily allows us to do the following:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Point(x=3, y=4)" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p = Point(3, 4)\n", "p" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "p.x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, other implementations exist. In the [travelling salesman problem](http://nbviewer.ipython.org/url/norvig.com/ipython/TSP.ipynb), Norvig uses complex numbers, which have the advantage of allowing easy (euclidian) distance computations:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "Point = complex\n", "\n", "def X(point): \n", " \"The x coordinate of a point.\"\n", " return point.real\n", "\n", "def Y(point): \n", " \"The y coordinate of a point.\"\n", " return point.imag\n", "\n", "def distance(A, B): \n", " \"The distance between two points.\"\n", " return abs(A - B)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.0" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A = Point(3, 4)\n", "B = Point(3, 5)\n", "distance(A, B)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, in [Gesture Typing](http://nbviewer.jupyter.org/url/norvig.com/ipython/Gesture%20Typing.ipynb), Norvig uses an even more clever variant:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "class Point(complex):\n", " \"A point in the (x, y) plane.\"\n", " def __repr__(self): return 'Point({}, {})'.format(self.x, self.y)\n", " x = property(lambda p: p.real)\n", " y = property(lambda p: p.imag)\n", " \n", "def distance(A, B):\n", " \"The distance between two points.\"\n", " return abs(A - B)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Point(0.0, 4.0)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A = Point(0, 4)\n", "A" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.605551275463989" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A = Point(2, 1)\n", "B = Point(5, 3)\n", "distance(A, B)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Norvig's approach to modeling algorithms " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another great aspect of the way Peter Norvig codes in his notebooks is the way he writes algorithms. In the travelling salesman, he writes the algorithm using objects that he hasn't defined yet:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "def alltours_tsp(cities):\n", " \"Generate all possible tours of the cities and choose the shortest tour.\"\n", " return shortest_tour(alltours(cities))\n", "\n", "def shortest_tour(tours): \n", " \"Choose the tour with the minimum tour length.\"\n", " return min(tours, key=tour_length)\n", "\n", "# TO DO: Data types: cities, tours, Functions: alltours, tour_length" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The **TO DO** allows him to explicitly document the symbols he has used but not yet defined. The interesting approach here is that this is exactly what humans do: we talk about concepts that exist in our heads, even though they don't have a concrete meaning, in a sort of lazy evaluation, and we elaborate about the details when needed in the conversation. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another look at Norvig's way at algorithms is found in the convex hulls notebook:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "def convex_hull(points):\n", " \"Find the convex hull of a set of points.\"\n", " if len(points) <= 3:\n", " return points\n", " # Find the two half-hulls and append them, but don't repeat first and last points\n", " upper = half_hull(sorted(points))\n", " lower = half_hull(reversed(sorted(points)))\n", " return upper + lower[1:-1]\n", "\n", "def half_hull(sorted_points):\n", " \"Return the half-hull from following points in sorted order.\"\n", " # Add each point C in order; remove previous point B if A->B-C is not a left turn.\n", " hull = []\n", " for C in sorted_points:\n", " # if A->B->C is not a left turn ...\n", " while len(hull) >= 2 and turn(hull[-2], hull[-1], C) != 'left':\n", " hull.pop() # ... then remove B from hull.\n", " hull.append(C)\n", " return hull" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the main algorithm, he uses the `half_hull` function before defining it. This is a great way of making problems more tractable." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## But, what's the point of this approach? " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The point of this approach is: by describing things in what is almost normal English language, the concrete problems become tractable. In particular, I would say that:\n", "\n", "> Good data type design + high level algorithm description = understandable and writable code" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For me, another good example of this is found in the gesture typing notebook. The keyboard has been defined as a dictionary, thus allowing direct access to letter coordinates, so we can simply *loop over the letters of a given word* to compute the total swiped distance (because we used complex numbers to represent 2d coordinates) over that word. This gives the beautiful following code:\n", "\n", "```python\n", "def path_length(word, kbd=qwerty):\n", " \"The total path length for a word on this keyboard: the sum of the segment lengths.\"\n", " return sum(distance(kbd[word[i]], kbd[word[i+1]])\n", " for i in range(len(word)-1))\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Debugging your code and writing files to disk " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Two other recurrent needs in the Hashcode competitions are debugging and writing files to disk. Of these two, I have to say that debugging is the biggest shortcoming in my current toolbox. I mostly code in the Jupyter notebook and debugging is doable, but not easy with it. \n", "\n", "Two ways of debugging are:\n", "\n", "- calling the magic debug fuction `%debug` when an exception fails launches a post-mortem inside the debugger\n", "- calling `%debug do(args)` allows one to step inside the call on that line\n", "\n", "Writing files to disk is the standard interface for submitting files to the Hashcode judge server. This is easy enough in Python, for example using the string format instruction:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'arg1: 1, arg2: 2'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"arg1: {}, arg2: {}\".format(1, 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**update 2018** Things have become even simpler with Python 3.6 and its *f-strings*:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'arg1: 1, arg2: 2'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a, b = 1, 2\n", "f\"arg1: {a}, arg2: {b}\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Visualization " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A recurring need in Hashcode problems is visualization. Basic visualization includes visualizing the input dataset, visualizing algorithm outputs. In particular, reimplementing a visual representation of the text output of the algorihtm usually saves time and effort because you don't have to wait for the Judge system to grade your submission. I believe this is in fact essential to success. Visualization is often the only eyes you can apply to the algorithm you're designing." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Checklist " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "I'd like to conclude this post by providing a little checklist of things that are part of the assignment in a typical Hashcode problem:\n", "\n", "- wisely choose the data types you'll use to model the problem\n", "- define the functions you'll want to use before implementing them\n", "- write your algorithm in as plain as possible English before going into the details\n", "- write an input file reader and visualize the input result\n", "- write an output file reader and visualize the output result\n", "- write a debugging visualization of your algorithm" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.1" }, "toc": { "colors": { "hover_highlight": "#DAA520", "navigate_num": "#000000", "navigate_text": "#333333", "running_highlight": "#FF0000", "selected_highlight": "#FFD700", "sidebar_border": "#EEEEEE", "wrapper_background": "#FFFFFF" }, "moveMenuLeft": true, "nav_menu": { "height": "172px", "width": "253px" }, "navigate_menu": true, "number_sections": true, "sideBar": true, "threshold": 4, "toc_cell": false, "toc_section_display": "block", "toc_window_display": false, "widenNotebook": false } }, "nbformat": 4, "nbformat_minor": 1 }