How to improve efficiency in loops?
Posted
by
Jacob Worldly
on Stack Overflow
See other posts from Stack Overflow
or by Jacob Worldly
Published on 2012-12-06T23:02:35Z
Indexed on
2012/12/06
23:03 UTC
Read the original article
Hit count: 240
python
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
© Stack Overflow or respective owner