问题描述
摩尔斯电码定义了一种标准编码,通过将每个字母映射到一系列点和短划线中,如下图所示:
26个字母的完整编码列表为:
{‘a’: ‘.-‘, ‘b’: ‘-…’, ‘c’: ‘-.-.’, ‘d’: ‘-..’, ‘e’: ‘.’, ‘f’: ‘..-.’, ‘g’: ‘–.’, ‘h’: ‘….’, ‘i’: ‘..’, ‘j’: ‘.—‘, ‘k’: ‘-.-‘, ‘l’: ‘.-..’, ‘m’: ‘–‘, ‘n’: ‘-.’, ‘o’: ‘—‘, ‘p’: ‘.–.’, ‘q’: ‘–.-‘, ‘r’: ‘.-.-‘, ‘s’: ‘…’, ‘t’: ‘-‘, ‘u’: ‘..-‘, ‘v’: ‘…-‘, ‘w’: ‘.–‘, ‘x’: ‘-..-‘, ‘y’: ‘-.–‘, ‘z’: ‘–..’}
给定一个单词列表,单词中的每个字母可以写成摩尔斯码。例如,将cba写成-.-.-….-,(把c、b、a的摩尔斯码串接起来)即为一个词的转换,返回所有单词的不同的转换数量。
示例
输入
words=['gin','zen','gig','msg'] ,输出为
2 ,这是因为:
‘gin’ —>‘–…-.’
‘zen’ —>‘–…-.’
‘gig’ —>‘–…–.’
‘msg’ —>‘–…–.’
换句话说这里存在两种不同的转换:’–…-.’和’–…–.’。
代码实现
def morse_representation(words):
# 输入单词列表
# 输出转换数量
morse = {'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..',
'e': '.', 'f': '..-.', 'g': '--.', 'h': '....',
'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..',
'm': '--', 'n': '-.', 'o': '---', 'p': '.--.',
'q': '--.-', 'r': '.-.-', 's': '...', 't': '-',
'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-',
'y': '-.--', 'z': '--..'}
# 创建一个set()区分数量
s = set()
for i in words:
mo = ''
for j in i:
mo += morse[j]
s.add(mo)
return len(s)
words = ['gin', 'zen', 'gig', 'msg']
print('输入单词组:', words)
print('输出不同变换的数量:', morse_representation(words))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
defmorse_representation(words):
# 输入单词列表
# 输出转换数量
morse={'a':'.-','b':'-...','c':'-.-.','d':'-..',
'e':'.','f':'..-.','g':'--.','h':'....',
'i':'..','j':'.---','k':'-.-','l':'.-..',
'm':'--','n':'-.','o':'---','p':'.--.',
'q':'--.-','r':'.-.-','s':'...','t':'-',
'u':'..-','v':'...-','w':'.--','x':'-..-',
'y':'-.--','z':'--..'}
# 创建一个set()区分数量
s=set()
foriinwords:
mo=''
forjini:
mo+=morse[j]
s.add(mo)
returnlen(s)
words=['gin','zen','gig','msg']
print('输入单词组:',words)
print('输出不同变换的数量:',morse_representation(words))
运行结果
输入单词组: ['gin', 'zen', 'gig', 'msg']
输出不同变换的数量: 2
1
2
输入单词组:['gin','zen','gig','msg']
输出不同变换的数量:2