要完成该程序,您需要使用递归算法,因为有很多可能的单词组合。
我已经更改了您的变量名称,以便它们易于理解它们保存的数据。
该decode
函数用作递归算法。第一行检查 Morse 是否为空,因此无需运行该函数,因为它是一个终点,它会打印该分支的输出。
该函数的其余部分将检查是否可以从前 i 个字母中组成一个单词。i
开头,1
因为这是最短的字母,最大长度是文件中的最大莫尔斯长度。while 循环还通过检查i
不大于 Morse 的长度来检查是否没有发生越界错误。
代码无法更改函数的参数,因为在相同的函数中可以找到其他单词,从而导致冲突,因此为更改的英语和莫尔斯语创建了新变量。检查可能单词的长度是否已被重复和允许。
from string import ascii_uppercase
#Defines the letter to Morse mapping
code = {
'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': '--..'
}
#Opens the file and reads all words
file = open("words.txt","r")
words = file.read()
file.close()
morse = words
# Converts all words to morse
for letter in list(ascii_uppercase):
morse = morse.replace(letter, code[letter])
# Creates list of the morse and english words from strings
morsewords = morse.split("\n")
engwords = words.split("\n")
# Finds the max length of morse words
maxlength = max([len(i)] for i in morsewords)[0]
# Creates a dictionary of {morse words : english words}
words = dict(zip(morsewords, engwords))
# MorseInput = input("Morse code :")
MorseInput = ".--....-....-.-..-----."
# This is the recursive function
def decode(morse, eng="", oneWord=False, twoWord=False):
# Print the english when finished
if morse == "":
print(eng)
else:
i = 1
# While loop allows to go through all possWord where condition met
while len(morse) >= i and i <= maxlength:
possWord = morse[:i]
# Checks if the word is a real word
if possWord in words.keys():
# Real word therefore add to english and the morse
newEng = eng + " " + words[possWord]
newMorse = morse[i:]
# Checks if that not more than one, One length word used
if len(words[possWord]) == 1:
if not oneWord:
decode(newMorse, newEng, True, twoWord)
# Checks if that not more than one, Two length word used
elif len(words[possWord]) == 2:
if not twoWord:
decode(newMorse, newEng, oneWord, True)
# Word is greater than two so doesn't matter
else:
decode(newMorse, newEng, oneWord, twoWord)
i += 1
decode(MorseInput)
我希望我的评论有点道理。
我确信代码可以做得更好更短,但我在不到一个小时内就完成了。
它打印
A TEST IF DOG
A DID IN DOG
A BLUE DOG
WEST I IN DOG
WEST IF DOG
WEST EVEN A ON