使用循环和字典解码摩尔斯电码程序

using loops and dictionaries for decoding a morse code program

我正在为摩尔斯电码编写编码和解码函数。编码功能有效,但解码功能多次给出相同的输出。有人可以看到我如何修复 for 循环以仅打印一次。顺便说一句,它是倒着打印的,因为我是这样打印的

解码函数的示例输入

....  .  .-..  .-..  --- 

预期输出

HELLO

输出

OLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEHOLLEH

我的代码

MORSE_CODES={'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':'--..'}


def decode_Morse(my_msg): 
 
  string=" "
  
  for morsecode in my_msg:
    wordsplit=my_msg.split()

    for ch in wordsplit:
      if ch!="  ":
        string=string+ list(MORSE_CODES.keys())[list(MORSE_CODES.values()).index(ch)] 
      else:
        ch=" "
      
  return string

def main()
     my_msg_reverse_Morse_plain=decode_Morse(my_msg_reverse_Morse)
     print("Plaintext of the previous Morse Code:",

简单的这个怎么样?

MORSE_DECODES = {v:k for k,v in MORSE_CODES.items()}
def decode_Morse(my_msg):
    return "".join(MORSE_DECODES[ch] for ch in my_msg.split())

您自己的代码使用了太多循环,试试这个:

def decode_Morse(my_msg): 
 
  string=""
  
  for morsecode in my_msg.split():
      string=string+list(MORSE_CODES.keys())[list(MORSE_CODES.values()).index(morsecode)]
      
  return string

如果您有多个单词,那么您必须为纯字母和单词使用不同的分隔符。例如,字母 space,单词 3,那么这将起作用:

def decode_Morse(my_msg): 
  string = ""
  for word in my_msg.split("   "):
      for ch in word.split():
          string=string+list(MORSE_CODES.keys())[list(MORSE_CODES.values()).index(ch)]
      string = string + " "
  return string

我认为最好定义一个反向字典,将摩尔斯电码映射到字符,然后将它们映射到代码:

# Reversed dictionary: 
my_msg = '....  .  .-..  .-..  --- '
rkey = {v:k for k,v in MORSE_CODES.items()}
answer = "".join(map(lambda x: rkey[x], my_msg.split()))
print(answer)
# HELLO