Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Properties and method overload solution in Clear category for Voice TV Control by vlad.bezden
from functools import singledispatchmethod
def to_yes_no(boolean):
"""Converts boolean value (True/False) to "Yes/No" string"""
return "Yes" if boolean else "No"
class VoiceCommand(list):
def __init__(self, channels):
super().__init__(channels)
self._current = 0
@property
def channel(self):
return self._current
@channel.setter
def channel(self, channel):
self._current = channel % len(self)
def first_channel(self):
self.channel = 0
return self.current_channel()
def last_channel(self):
self.channel = len(self) - 1
return self.current_channel()
def turn_channel(self, channel):
self.channel = channel - 1
return self.current_channel()
def next_channel(self):
self.channel += 1
return self.current_channel()
def current_channel(self):
return self[self.channel]
def previous_channel(self):
self.channel -= 1
return self.current_channel()
@singledispatchmethod
def is_exist(self):
raise NotImplementedError("Supported types are int and str")
@is_exist.register
def _(self, channel: int):
return to_yes_no(channel <= len(self))
@is_exist.register
def _(self, channel: str):
return to_yes_no(channel in self)
if __name__ == "__main__":
CHANNELS = ["BBC", "Discovery", "TV1000"]
controller = VoiceCommand(CHANNELS)
assert controller.first_channel() == "BBC"
assert controller.last_channel() == "TV1000"
assert controller.turn_channel(1) == "BBC"
assert controller.next_channel() == "Discovery"
assert controller.previous_channel() == "BBC"
assert controller.current_channel() == "BBC"
assert controller.is_exist(4) == "No"
assert controller.is_exist("TV1000") == "Yes"
controller.turn_channel(3)
controller.next_channel()
controller.current_channel()
print("PASSED")
Feb. 26, 2020
Comments: