【发布时间】:2020-09-06 09:02:13
【问题描述】:
想出了“o”的意思。它采用列表中的第二个元素,而不是列表中的第二个列表。但现在我又回到了间距问题...
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', '-----': '0',
'.----': '1', '..---': '2', '...--': '3',
'....-': '4', '.....': '5', '-....': '6',
'--...': '7', '---..': '8', '----.': '9'
}
def morse_decoder(code):
words = code.split(" ")
words2d = []
for i in words:
words = i.split()
words2d.append(words)
array = []
for j in range(len(words2d)):
for k in range(len(words2d[j])):
array.append(MORSE[words2d[j][k]])
array.append(" ")
string = "".join(array)
return string.capitalize()
if __name__ == '__main__':
print("Example:")
print(morse_decoder('... --- ... ...'))
print(morse_decoder("... --- -- . - . -..- -"))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert morse_decoder("... --- -- . - . -..- -") == "Some text"
assert morse_decoder("..--- ----- .---- ---..") == "2018"
assert morse_decoder(".. - .-- .- ... .- --. --- --- -.. -.. .- -.--") == "It was a good day"
print("Coding complete? Click 'Check' to earn cool rewards!")
您会注意到我的输出是“一些文本”,用于输入“... --- -- . - . -..- -”而不是“一些文本”(末尾没有空格)。看来我的第一个问题的解决方案已经创建了一个新问题。接近...任何指导表示赞赏。谢谢。
所以我最初的获得正确间距的问题得到了解决。但经过进一步测试,我没有得到我想要的结果。我说我想要“Sos o”,这就是现在正在打印的内容。但我真正想要的是那个输入的“Sos s”。
问题似乎在于我对 words2d 列表的定义。我想要完成的是将每个单词的莫尔斯电码包含在自己的列表中。但是由于某种原因,我真的很想理解它正确地创建了第一个单词列表,但是第二个单词是“o”的莫尔斯电码。 Stefan 在下面给了我一些替代代码来执行该函数的基本任务(将莫尔斯电码翻译成英语),但我仍然想知道我的代码出了什么问题。
我正在创建一个函数来解码莫尔斯电码消息,但在最终字符串中实现适当的间距时遇到了困难。基本上,我希望每个单词之间有一个空格。而且我只能设法实现完全没有间距(如下面的代码)或每个字母之间的空格,这也是不可取的。我故意在下面的代码中组织了 words2d 列表,以便每个(编码的)单词都在自己的列表中,我想我可能走在正确的轨道上,但不知道从那里去哪里。
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', '-----': '0',
'.----': '1', '..---': '2', '...--': '3',
'....-': '4', '.....': '5', '-....': '6',
'--...': '7', '---..': '8', '----.': '9'
}
def morse_decoder(code):
words = code.split(" ")
words2d = []
for i in range(len(words)):
words = words[i].split()
words2d.append(words)
array = []
for j in range(len(words2d)):
for k in range(len(words2d[j])):
array.append(MORSE[words2d[j][k]])
array.append(" ") #This is the line I was missing initially
string = "".join(array)
return string.capitalize()
print(morse_decoder('... --- ... ...')) #should print "Sos s"
【问题讨论】:
-
嘿亚伦。欢迎来到堆栈溢出。你能提供给我们你得到的输出吗?
-
我得到以下输出:Soso
标签: python list dictionary spacing