python-checkio/ScientificExpedition/morse-clock.py

45 lines
1.4 KiB
Python
Raw Normal View History

2019-12-19 16:34:23 +01:00
def checkio(time_string: str) -> str:
time_string = time_string.split(":")
hour = time_string[0].rjust(2, "0")
minute = time_string[1].rjust(2, "0")
second = time_string[2].rjust(2, "0")
return "{}: {}: {}".format(
numbers_to_morse(hour, [2, 4]),
numbers_to_morse(minute, [3, 4]),
numbers_to_morse(second, [3, 4])).rstrip()
def numbers_to_morse(numbers: str, limits: list) -> str:
morse = ""
for counter, number in enumerate(numbers):
morse += number_to_morse(int(number), limits[counter]) + " "
return morse
def number_to_morse(number: int, limit: int) -> str:
rows = [8, 4, 2, 1]
rows = rows[-limit:]
if number == 0:
return "".rjust(limit, ".")
morse = ""
for row in rows:
if number - row >= 0:
morse += "-"
number -= row
else:
morse += "."
return morse
if __name__ == '__main__':
print("Example:")
print(checkio("10:37:49"))
# These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio("10:37:49") == ".- .... : .-- .--- : -.. -..-", "First Test"
assert checkio("21:34:56") == "-. ...- : .-- .-.. : -.- .--.", "Second Test"
assert checkio("00:1:02") == ".. .... : ... ...- : ... ..-.", "Third Test"
assert checkio("23:59:59") == "-. ..-- : -.- -..- : -.- -..-", "Fourth Test"
print("Coding complete? Click 'Check' to earn cool rewards!")