How to improve efficiency in loops?
- by Jacob Worldly
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