Wednesday, February 27, 2013

99 bottles of beer - Python

This one is pretty useless, I know. I was trying to think up something to code to test out my fledgling Python knowledge back when I was first picking it up. There was a competition online to script something to output the lyrics to "99 bottles of beer on the wall" in the fewest lines possible. There was a category for fewest characters as well. I knew I wasn't good enough to enter such a competition, but I figured I'd try it and see what I could come up with.

Here's what I ended up doing:

def outputLine(x,v):
  z = str(x) + " bottle" + v + " of beer on the wall, " + str(x) + " bottle" + v + " of beer. take one down pass it around, " + str(x-1) + " bottles of beer on the wall."
  print z
def song():
  boosh = range(1, 100)
  boosh.reverse()
  for x in boosh:     
    if x == 1:
      v = ""
      outputLine(x,v)
    else:
      v = "s"
      outputLine(x,v)
      x = x - 1   
song()

works like a champ
I know now, several shortcuts I could use to shorten it up a bit more, but it's interesting for me to see how I solved a problem a year ago and think about how I would do it now.

-newt

No comments:

Post a Comment