Reputation: 3
Working with a morse code translator!
I have a program that gets an input from a user, to example "Hello", and then I need to read of each character and transform it to morse code time units.
The way I do it is that I use short period for 0 and long period for 1. I made a lot of variables from A-Z, 0-9, and wrote "byte" code for each. It got pretty big.
Then eventually I had to make a function that reads the input and puts all the zeros and ones in one big string with help of these variables I made. And here I got stuck, because I wasn't ready to make 35 if statements.
'''
Function that compiles all the letters from input together
to a 0/1 code
'''
morse = "" # the string that will include "byte code"
def compile(text):
for c in text:
# here I got stuck
# Alphabet
A = "01"
B = "1000"
C = "1010"
D = "100"
E = "0"
# .....
I would like to know if there is any actual solution to this mess, how to write this function without overusing if statements.
I tried to be clear as possible, hope you understand.
Upvotes: 0
Views: 144
Reputation: 98
Your best bet will be to use a dictionary. Compile it like so:
alphabet = {
"A": "01"
"B": "02"
...
"Z": "01111010"
}
And then in your for loop, you can do:
def compile(text):
morse_string = ""
for c in text.upper():
morse_string += alphabet[c]
return morse_string
Or something along those lines.
You can find more about dictionaries (and other datastructures) here.
Upvotes: 1
Reputation: 780994
Use a dictionary to map from letters to codes.
morse_dict = {"A": "01", "B": "1000", "C": "1010", ...}
def compile(text):
return " ".join(morse_dict[c] for c in text.upper())
Upvotes: 0