I am a beginner in Python, and I made a Morse translator that converts letters to Morse, and Morse to letters (where a decimal point is 'dot' and underscore is 'dash'). Is there any way I could make my code shorter and more efficient? For reference, here's the translation of Morse to letter characters.
dot = '.'
dash = '_'
letter_list = ['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']
morse_list = [dot + dash, dash + dot * 3, dash + dot + dash + dot, dash + dot * 2, dot, dot * 2 + dash + dot,
dash * 2 + dot, dot * 4, dot * 2, dot + dash * 3, dash + dot + dash, dot + dash + dot * 2,
dash * 2, dash + dot, dash * 3, dot + dash * 2 + dot, dash * 2 + dot + dash, dot + dash + dot,
dot * 3, dash, dot * 2 + dash, dash * 3 + dot, dot + dash * 2, dash + dot * 2 + dash,
dash + dot + dash * 2, dash * 2 + dot * 2]
# The for loop below prints the entire translation (Eg. 'A: ._ B: _...') so the user could reference it
for n in range(len(letter_list)):
print(letter_list[n] + ': ' + morse_list[n], sep=' ', end=' ', flush=True)
while True:
print("\nTYPE 'EXIT' if you want to EXIT.")
user_input = input("INPUT LETTERS OR MORSE CHARACTERS (DECIMAL AND UNDERSCORE) TO CONVERT."
"\nSEPERATE LETTERS WITH SPACES: ")
# Converts user input into an iterable list
user_list = user_input.split()
if user_input == 'EXIT':
print("THANK YOU FOR USING THE MORSE TRANSLATOR")
break
for i in range(len(user_list)):
if user_list[i] in letter_list:
for n in range(len(morse_list)):
if user_list[i] == letter_list[n]:
print(morse_list[n], sep=' ', end=' ', flush=True)
elif user_list[i] in morse_list:
for n in range(len(letter_list)):
if user_list[i] == morse_list[n]:
print(letter_list[n], sep=' ', end=' ', flush=True)
dictionary
\$\endgroup\$A: '.-'
instead, this saves the multiplication and addition cost \$\endgroup\$• and —
rather than. and _
. If it's in a variable, i would only have to change 2 lines, rather than an entire dictionary. \$\endgroup\$Concatenation
of strings are relatively expensive but its okay for this scenario, but do keep that in mind. \$\endgroup\$