【Python CheckiO 题解】Multicolored Lamp


CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,本博客主要记录自己用 Python 在闯关时的做题思路和实现代码,同时也学习学习其他大神写的代码。

CheckiO 官网:https://checkio.org/

我的 CheckiO 主页:https://py.checkio.org/user/TRHX/

CheckiO 题解系列专栏:https://itrhx.blog.csdn.net/category_9536424.html

CheckiO 所有题解源代码:https://github.com/TRHX/Python-CheckiO-Exercise


题目描述

【Multicolored Lamp】:新年快到了,您已经决定要装修房屋。但是简单的灯光和圣诞节装饰太无聊了,因此您已经意识到可以使用编程技巧来创建一些非常酷和新颖的东西。您的任务是创建类 Lamp() 和方法 light(),它们将使灯以序列中的四种颜色之一(Green, Red, Blue, Yellow)发光。第一次使用 light() 方法时,颜色应为 Green,第二次应为 Red,依此类推。如果当前颜色为 Yellow,则下一个颜色应为 Green,依此类推。

【链接】https://py.checkio.org/mission/multicolored-lamp/

【输入】:字符串,表示打开灯的次数

【输出】:灯的颜色

【前提】:4 colors: Green, Red, Blue, Yellow.

【范例】

lamp_1 = Lamp()
lamp_2 = Lamp()

lamp_1.light() #Green
lamp_1.light() #Red
lamp_2.light() #Green
    
lamp_1.light() == "Blue"
lamp_1.light() == "Yellow"
lamp_1.light() == "Green"
lamp_2.light() == "Red"
lamp_2.light() == "Blue"

代码实现

colors = ['Green', 'Red', 'Blue', 'Yellow']


class Lamp:
    def __init__(self):
        self.count = 0

    def light(self):
        if self.count == 4:
            self.count = 0
            color=colors[self.count]
        else:
            color=colors[self.count]
            self.count += 1
        return color


if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing

    lamp_1 = Lamp()
    lamp_2 = Lamp()

    lamp_1.light() #Green
    lamp_1.light() #Red
    lamp_2.light() #Green
    
    assert lamp_1.light() == "Blue"
    assert lamp_1.light() == "Yellow"
    assert lamp_1.light() == "Green"
    assert lamp_2.light() == "Red"
    assert lamp_2.light() == "Blue"
    print("Coding complete? Let's try tests!")

大神解答

大神解答 NO.1

from itertools import cycle

class Lamp:
    sequence = ('Green', 'Red', 'Blue', 'Yellow')

    def __init__(self):
        self.lights = cycle(Lamp.sequence)
    
    def light(self):
        return next(self.lights)

大神解答 NO.2

from itertools import cycle

class Lamp(cycle):
    __new__ = lambda cls: cycle.__new__(cls, 'Green Red Blue Yellow'.split())
    light = cycle.__next__

大神解答 NO.3

from itertools import cycle

sequence = ('Green', 'Red', 'Blue', 'Yellow')
Lamp = type('', (), {'__init__': lambda s: setattr(s, 'c', cycle(sequence)), 'light': lambda s: next(s.c)})
发布了149 篇原创文章 · 获赞 518 · 访问量 46万+

猜你喜欢

转载自blog.csdn.net/qq_36759224/article/details/103577098
今日推荐