Python golf competition

Posted by on November 23, 2008

I have written a few entries on python golf before, but I have now decided to make an official competition from it. The rules are fairly simple: I pose a problem simple problem which must be solved (in python) in the lowest number of characters (where a new line counts as one byte). Solutions may be written for any 2.x version of python (ie, 2.3, 2.4, 2.5 or 2.6), and may use any library found on default install on a Debian machine.

Solutions must be emailed to me. In the case where two people have the same character count, the solution that arrived in my inbox first will be declared the winner (this is to stop people from playing with the date header in the email ^^). The winner will receive a chocolate bar or coffee — their choice.

The problem this week is one of parsing log files. You must parse a log file in the common log format that will be given on to your program on stdin. You must then print on stdout the amount of data that was sent to each ip address (and the ip address). A sample program has been provided:

#!/usr/bin/env python2.5
# Copyright 2008 Greg Darke <greg+laptop@tsukasa.net.au>
# Licensed for distribution under the GPL version 2, check COPYING for details
# Sample program to show the output format for the python golf problem posed at
# http://blag.tsukasa.net.au/2008/11/23/python-golf-competitionpython-golf-competition/

import re, sys

def main():
    clf_regexp = re.compile(r'''^(\S+)\s(\S+)\s(\S+)\s\[([^\]]*)\]\s"([^"]*)"\s(\d*)\s(\d*)$''')
    mapping = {}

    for line in sys.stdin:
        m = clf_regexp.match(line)
        if not m:
            continue
        ip, _, _, _, _, _, size = m.groups()
        size = int(size)

        if ip not in mapping:
            mapping[ip] = 0

        mapping[ip] += size

    for ip in mapping:
        print '%s %d' % (ip, mapping[ip])

if __name__ == "__main__":
    main()

Solutions will be accepted until 11:59:59pm(EDT) on Friday 28th November 2008.

Comments

Respond | Trackback

Comments

Comments: