编写一个程序,该程序可以读取一个单词并确定可以代表多少个单词(与输入的字母数量相同)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了编写一个程序,该程序可以读取一个单词并确定可以代表多少个单词(与输入的字母数量相同)相关的知识,希望对你有一定的参考价值。
这是摩尔斯电码问题的一部分。我想弄清楚从已编码的莫尔斯电码中可以制造多少个单词,以确保所输入的单词与输入的长度相同。
morseCode = {"A":".-","B":"-...","C":"-.-."}
morseCode["D"] = "-.."
morseCode["E"] = "."
morseCode["F"] = "..-."
morseCode["G"] = "--."
morseCode["H"] = "...."
morseCode["I"] = ".."
morseCode["J"] = ".---"
morseCode["K"] = "-.-"
morseCode["L"] = ".-.."
morseCode["M"] = "--"
morseCode["N"] = "-."
morseCode["O"] = "---"
morseCode["P"] = ".--."
morseCode["Q"] = "--.-"
morseCode["R"] = ".-."
morseCode["S"] = "..."
morseCode["T"] = "-"
morseCode["U"] = "..-"
morseCode["V"] = "...-"
morseCode["W"] = ".--"
morseCode["X"] = "-..-"
morseCode["Y"] = "-.--"
morseCode["Z"] = "--.."
#Retrieve end-user's message and convert it to upper case.
message = input("Type a message to convert in morse code (e.g. \"SOS\"?)").upper()
encodedMessage = ""
#Convert each letter into Morse code:
for character in message:
#Check that the character is in the Morse Code dictionary (e.g letter of the alphabet)
if character in morseCode:
encodedMessage += morseCode[character]
else:
#Replace unrecognised characters with a space
encodedMessage += ""
#Display the message in Morse code:
print("Your message in Morse code is:")
print(encodedMessage)
输入:eta
您在摩尔斯电码中的信息是:.-.-
输出:3
作为3个与eta长度相同的单词,可以使用已编码的莫尔斯电码。 (eta,ent,aet)
我不知道如何找到可以用摩尔斯电码编写的单词数。
答案
这样的事情没有优化:
morseCode = {
"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": "--.."
}
words = []
def countWords(msg, length = None, collected = ''):
if length is None:
length = len(msg)
if not msg:
if length == 1:
words.append(collected)
return 1
return 0
current = 0
for letter, code in morseCode.items():
if msg.startswith(code):
current += countWords(msg[len(code):], length - 1, collected + letter)
return current
if __name__ == '__main__':
#Retrieve end-user's message and convert it to upper case.
message = input('Type a message to convert in morse code (e.g. "SOS"): ').upper()
encodedMessage = ""
#Convert each letter into morse code:
for character in message:
#Check that the character is in the moreCode dictionary (e.g letter of the alphabet)
if character in morseCode:
encodedMessage += morseCode[character]
else:
#Replace unrecognised characters with a space
encodedMessage += ""
#Display the message in morse code:
print("Your message in morse code is:", encodedMessage)
print("There are", countWords(encodedMessage), "that match:")
for word in words:
print(word)
以及您的示例:
>py bla.py
Type a message to convert in morse code (e.g. "SOS"): ent
Your message in morse code is: .-.-
There are 3 that match:
AET
ENT
ETA
以上是关于编写一个程序,该程序可以读取一个单词并确定可以代表多少个单词(与输入的字母数量相同)的主要内容,如果未能解决你的问题,请参考以下文章