小屁孩日记3里的牛奶歌挺有意思的,和99个瓶子差不多,使用Python实现一下:
# -*- coding: utf-8 -*- # 小屁孩日记3 牛奶歌 哈哈 from sys import exit class Song: def __init__(self, num_of_bottles): self.bottles = num_of_bottles def zero(self): return self.bottles == 0 def take_one_down(self): if self.bottles != 0: self.bottles -= 1 return str(self.bottles) + (' bottle' if self.bottles == 1 else ' bottles') + ' of the beer.' if self.bottles != 0 else 'No more beer on the wall' def sing(self): if self.zero(): raise StopIteration else: yield str(self.bottles) + (' bottle' if self.bottles == 1 else ' bottles') + ' beer on wall, ' + 'take one down, ' + 'pass it around.' + self.take_one_down() song = Song(5) while True: try: print song.sing().next() except Exception: exit(0)