I have the following code, which translates the input string into morse code. My code runs through every letter in the string and then through every character in the alphabet. This is very inefficient, because what if I was reading from a very large file, instead of a small alphabet string. Is there any way that I could improve my code, Maybe using the module re, to match my string with the morse code characters?
morse_alphabet = ".- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --.."
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
morse_letters = morse_alphabet.split(" ")
result = []
count_character = 0
def t(code):
for character in code:
count_letter = 0
for letter in ALPHABET:
lower_character = code[count_character].lower()
lower_letter = letter.lower()
if lower_character == lower_letter:
result.append(morse_letters[count_letter])
count_letter += 1
count_character += 1
return result
You can use
string.ascii_lowercasetogether withzip()to make a dictionary instead:The
tfunction is reduced to afilter()and a generator expression looping over each character in the input code.The
morse_lettersdictionary now makes for a very fast lookup of codes, thefilter()removes theNoneresults for anything that isn’t a letter.Result: