It’s been a while since I put up one of these simple code posts. Let me fix that. :P
Quiet a while ago, this code needed to have the dust blown off of it. Programming Praxis had its readers program out the song for “Nintey-Nine Bottles of Beer on the Wall".
Here is my version of it:
#!/usr/bin/env python from __future__ import print_function def output(in_int): if in_int != 1: return "%d bottles of beer on the wall, %d bottles of beer." \ "You take one down, pass it around, %d bottles of beer" \ "on the wall." % (in_int,in_int, in_int - 1) else: return "%d bottle of beer on the wall, %d bottle of beer." \ "You take one down, pass it around, %d bottles of beer" \ "on the wall." % (in_int,in_int, in_int - 1) if __name__ == "__main__": [ print(output(x)) for x in reversed(xrange(1,99)) ]
That’s all there is to it really. The only enlightening thing about this I can say is that this algorithm reminds me a lot of my Code to lyrics post I wrote a little over a year ago. It’s amazing how simple songs are when they’re broken down to their basic elements. Anyone feel like setting up an “automatic song generation” business with me?

instead of reversed
I would:
[ print(output(x)) for x in xrange(99,1,-1)) ]
DOH, you're right Leszek. I
DOH, you're right Leszek. I totally forgot I could do that. MEMORY FAIL!
Of course not a problem in case of 99 bottles :)
But in a case of fast, heavy drinkers... :)
How about this?
def output(in_int):
plural = in_int-1 and 's' or ''
return "%d bottle%s of beer on the wall, %d bottle%s of beer." \
"You take one down, pass it around, %d bottles of beer" \
"on the wall." % (in_int, plural, in_int, plural, in_int - 1)
Hey Sean, agf's comments
Hey Sean, agf's comments aside, that is a neat little hack that would definitely cut down on the size of the output function. Thanks for sharing it.
Python has a conditional expression now
Don't use the and / or hack. There is a real conditional expression in Python, introduced in version 2.5, which works even if the "True" result (in your example, 's') evaluates to "False".
's' if in_int - 1 else ''I didn't know that Python had
I didn't know that Python had conditional expressions. I will have to write some code just to check it out. Thanks!
i even don't know about that
i even don't know about that functionality as i am new to python thanks for that . it really help me a lot.
MMA News
Why? and/or works just fine
Why? and/or works just fine in this case, and the if/else syntax is ugly and inside-out.
Post new comment