zoukankan      html  css  js  c++  java
  • 小屁孩日记 牛奶歌的Python实现

    小屁孩日记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)
  • 相关阅读:
    Java学习
    机器学习
    机器学习
    Java 学习
    哈希表复习
    [转] 数据库设计步骤
    Java
    c++的函数重载-笔记
    进程与线程-笔记
    内存知识-笔记
  • 原文地址:https://www.cnblogs.com/jaw-crusher/p/3485115.html
Copyright © 2011-2022 走看看