前言
前一段时间逛checkio,又发现一个有意思的题,是关于摩尔斯电码的。其实题本身素质一般,只是看到一个大佬的解法,真是让我大开眼界,学了很多。
一、题目说明
题目要求很简单,将一段时间格式的字符串转换为摩尔斯密码,转换规则见下图:
每一位都由不同长度的小球表示,灰色小球表示1,也就是True,白色球表示0,也就是False。不同的长度对应的数字分别是2的n次方:1, 2, 4, 8。
最后,1用-替换,0用.替换,连接起来就是一段摩尔斯密码了。
例如,“10 : 37 : 49”,可以用"01 0000 :011 0111 : 100 1001"表示,再转换一下,就是".- … : .-- .— : -… -…-"。
如果某一位只有一位数字,用0补齐,例如" 11 : 1 : 12"要转换为"11 : 01 : 12"。
好了,有关题目的介绍就到这里了,大家要不要试着编写一下函数,实现任意时间字符串的转换!
二、代码展示
下面直接展示一个我认为比较厉害的代码,也是网站获赞比较高的:
TO_MORSE = str.maketrans('01', '.-')
def to_morse(number, bits):
"""Return number in binary-Morse as a string with the given number of bits."""
return "{0:0{1}b}".format(number, bits).translate(TO_MORSE)
def to_code(field):
"""Return a space-delimited string of binary-Morse digits."""
tens, ones = divmod(int(field), 10)
return "{} {}".format(to_morse(tens, 3), to_morse(ones, 4))
def checkio(data):
"""Return a string representing the time in a Morse code-like form."""
return ' : '.join(map(to_code, data.split(':')))[1:] # Strip leading .
if __name__ == '__main__':
assert checkio("10:37:49") == ".- .... : .-- .--- : -.. -..-", "First Test"
assert checkio("21:34:56") == "-. ...- : .-- .-.. : -.- .--.", "Second Test"
assert checkio("11:10:12") == ".- ...- : ..- .... : ..- ..-.", "Third Test"
assert checkio("23:59:59") == "-. ..-- : -.- -..- : -.- -..-", "Fourth Test"
三、代码分析
1. str.maketrans()
此函数实现字符串之间的相互转换,类似replace,区别是可以一次转换多个字符,需要借助translate()
方法。用法如下:
>>> intab = "aeiou"
>>> outtab = "12345"
>>> test = "this is a test string"
>>> trans = str.maketrans(intab, outtab)
>>> result = test.translate(trans)
>>> print(result)
th3s 3s 1 t2st str3ng
2. 以二进制位基数格式化输出
另一个巧妙的方法是,通过"{0:0{1}b}".format(number, bits)"
直接快速的以二进制形式输出了0,1格式的字符串。
四、总结
这个题自认为不是很难,怎奈自己没有想到最重要的二进制格式化输出,导致走了弯路。因此在此记录,与大家一同分享一下。