Voting

Category

real language

Bookmarking

Del.icio.us Digg Diigo DZone Earthlink Google Kick.ie
Windows Live LookLater Ma.gnolia Reddit Rojo StumbleUpon Technorati

Language Python

(Using a iterator class)

Date:01/20/06
Author:Eric Moritz
URL:http://eric.themoritzfamily.com
Comments:2
Info:http://www.python.org
Score: (2.64 in 44 votes)
class Song:
    def __init__(self):
        self.n = 100

    def __iter__(self):
        return self

    def next(self):
        if self.n == 0:
            raise StopIteration
        self.n = self.n - 1
        return self._get_verse(self.n)
    
    def _get_verse(self,n):
        lines = []
        data  = []
        if n > 1:
            data.append(["%s bottles" % n,"%s bottles" % n])
            data.append(["Take one down pass it around","%s bottles" % (n-1)])
        elif n == 1:
            data.append(["%s bottle" % n,"%s bottle" % n])
            data.append(["Take one down pass it around","%s bottles" % "no more"])
        elif n == 0:
            data.append(["No more bottles","no more bottles"])
            data.append(["Go to the store and buy some more","%s bottles" % 99])
            
        lines.append("%s of beer on the wall, %s of beer" % tuple(data[0]))
        lines.append("%s, %s of beer on the wall" % tuple(data[1]))
        lines.append("")
        return "\n".join(lines)

song = Song()
for stanza in song:
    print stanza

Download Source | Write Comment

Alternative Versions

VersionAuthorDateCommentsRate
This example demonstrates the simplicityGerold Penz07/23/0515
Creative versionSchizo11/06/0516
Advanced, extensible beer/wall frameworkJamie Turner05/17/067
minimal versionOliver Xymoron04/20/055
using lambda in LISP styleJ Adrian Zimmer11/14/062
Exception basedMichael Galpin02/08/080
functional, w/o variables or proceduresIvan Tkatchev07/14/052
minimal version with singularEmlyn Jones06/13/053
Fully compliant versionRicardo Garcia Gonzalez01/15/067
New conditional expressions in 2.5Ezequiel Pochiero12/18/061

Comments

>>  zefciu said on 06/27/06 16:29:06

zefciu I think the most pythonish example.

>>  Ian said on 07/06/06 03:56:32

Ian Better would be to take the number of verses as an __init__ parameter.

Download Source | Write Comment

Add Comment

Please provide a value for the fields Name, Comment and Security Code.
This is a gravatar-friendly website.
E-mail addresses will never be shown.
Enter your e-mail address to use your gravatar.

Please don't post large portions of code here! Use the form to submit new examples or updates instead!

Name:

eMail:

URL:

Security Code:
  
Comment: