基本上,我必须使用两个函数制作莫尔斯电码编码器和解码器。我的教授的模板(当然,我已经为第一个函数和主函数添加了代码(包括一个全局变量,我不知道如何使用它。此外,我在当前代码中遇到了一个错误,因为字母在某种程度上是一个整数,而不是字符串。有人能解释一下我如何在这个程序中使用全局变量吗?因为我现在不担心错误?
MORSE_CODES=[' .- ',' -... ',' -.-. ',' -.. ',' . ',' ..-. ',' --. ',' .... ',' .. ',
' .--- ',' -.- ',' .-.. ',' -- ',' -. ',' --- ',' .--. ',' --.- ',' .-. ',
' ... ',' - ',' ..- ',' ...- ',' .-- ',' -..- ',' -.-- ',' --.. ']
ASCII_A=65 #global var
def encode_Morse(my_msg):
my_msg_Morse=(my_msg.upper())
my_msg_Morse=my_msg_Morse.replace(" "," ")
for letter in range(0, len(my_msg_Morse)):
if ord(letter)>=65 and ord(letter)<=90:
my_msg_Morse=my_msg_Morse.replace(letter, MORSE_CODES[letter])
else:
my_msg_Morse=my_msg_Morse.replace(letter,'*')
my_msg_Morse=my_msg_Morse+" "+letter
return my_msg_Morse
**#def decode_Morse(my_msg):
my_msg_Morse=my_msg.split(" ")
string=""
for word in my_msg_Morse:**
def main():
my_msg=input("Enter your message: ")
my_msg=my_msg.upper()
print("Your message in plain text: ", my_msg)
my_msg_Morse=encode_Morse(my_msg)
print("Your message in Morse Code: ", my_msg_Morse)
问题
for letter in range(0, len(my_msg_Morse)):
不会循环消息中的字母my_msg_Morse=my_msg_Morse.replace(letter, MORSE_CODES[letter])
导致用空格替换消息中的莫尔斯电码字母(即多字消息(- 关于全局变量——如果你只需要使用它们的值(你在这里(,就可以使用它们
代码
MORSE_CODES=[' .- ',' -... ',' -.-. ',' -.. ',' . ',' ..-. ',' --. ',' .... ',' .. ',
' .--- ',' -.- ',' .-.. ',' -- ',' -. ',' --- ',' .--. ',' --.- ',' .-. ',
' ... ',' - ',' ..- ',' ...- ',' .-- ',' -..- ',' -.-- ',' --.. ']
ASCII_A=65 #global var
def encode_Morse(my_msg):
result = ''
for letter in my_msg_Morse:
if 65 <= ord(letter) <= 90:
if not result:
result = MORSE_CODES[ord(letter)-ASCII_A] # first Morse character
else:
result += ' ' + MORSE_CODES[ord(letter)-ASCII_A] # space between Morse character
else:
result += '*'
return result
def decode_Morse(my_msg):
for i, code in enumerate(MORSE_CODES):
my_msg = my_msg.replace(code, chr(i+65))
return my_msg.replace('*', ' ')
def decode_Morse_using_counter(my_msg):
' Version using counter rather than enumerate to track index '
i = 0
for code in MORSE_CODES:
my_msg = my_msg.replace(code, chr(i+65))
i += 1
return my_msg.replace('*', ' ')
def main():
my_msg = input("Enter your message: ")
my_msg = my_msg.upper().replace(' ', ' ') # upper case with 3 letters between words
print("Your message in plain text: ", my_msg)
encode_msg = encode_Morse(my_msg)
print("Your message in Morse Code: ", encode_msg)
print("Decoded Morse Code: ", decode_Morse(encode_msg))
main()
示例运行
Enter your message: This is a simple message
Your message in plain text: THIS IS A SIMPLE MESSAGE
Your message in Morse Code: - .... .. ... *** .. ... *** .- *** ... .. -- .--. .-.. . *** -- . ... ... .- --. .
Decoded Morse Code: THIS IS A SIMPLE MESSAGE
函数重写
使用列表理解和Walrus运算符,encode_Morse函数可以简化为:
def encode_Morse(my_msg):
my_msg_Morse = my_msg.upper()
return ''.join(MORSE_CODES[p-ASCII_A] if 65 <=(p:=ord(letter))<= 90 else '*' for letter in my_msg_Morse)