Friday, February 08, 2008

99 Bottles of Beer

First off, if you like programming, you should check out this hilarious site on the venerable song 99 Bottles of Beer.

Ok, now I am assuming that you just spent the last hour or so at that website, but you are back. If you are into Java, one of the most interesting solutions is one that eschews typical control structures (for/while/do loops) and instead uses Java's exception system to sing the song. Actually the way that I came across the site was from an email sent by one of my colleagues. He was amused by the exception based solution. I was amused, too. Obviously such code will perform exceptionally bad (pun intended.)

One of my friends was inspired to do a Python variant that used the same technique:


#! /usr/bin/env python

class BottleException(Exception):
def __init__(self, i, c):
self.cause = c
self.cnt = i
try:
a = 1/(99-i)
raise BottleException(i+1, self)
except ZeroDivisionError:
pass

def getCause(self):
return self.cause

def printStackTrace(self):
print("%d Bottle(s) of beer on the wall, %d Bottle(s) of beer" % (self.cnt, self.cnt))
print("Take one down and pass it around,")
print("%d Bottle(s) of beer on the wall" % (self.cnt - 1))
try:
self.getCause().printStackTrace()
except AttributeError:
pass

try:
raise BottleException(1, None)
except Exception, e:
e.printStackTrace()


He and I are both pure hackers when it comes to Python, so there are probably numerous improvements that can be done to that code.

Update: I submitted the Python code to the 99 Bottles of Beer site and they accepted it. You can view it here.

1 comment:

Anonymous said...

Hi! Just saw this solution while searching for python code samples. THX.

I've written original solution in java. However, people that I would call creators of such style are anonymous contributors of one of popular OS projects from jakarta. Few years ago my team encountered critical performance problem on production server. We tracked it down to few dozens of exceptionally weird code, which was heavily using exceptions for controlling flow of program... And yes - You are right - it was performing exceptionally bad (this is very well(and not so exceptionally) observable for java).
jarekr