Примерно так без оптимизации:
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": "--.."
}
def countWords(msg, length, collected = ''):
if not msg:
if not length:
return [collected]
return []
current = []
for letter, code in morseCode.items():
if msg.startswith(code):
current.extend(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)
matches = countWords(encodedMessage, len(message))
print("There are", len(matches), "that match:")
for word in matches:
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