I finally got around to whipping this up. It’s crude, but it’s a start. The next thing I need to do is fix the code tags for coldspell. They’re not behaving like good little tags should.
#Python morse code translator
morse_code = {'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':'--..','0':'-----','1':'.----','2':'..---',
'3':'...--','4':'....-','5':'.....','6':'-.... ',
'7':'--...','8':'---..','9':'----.',' ':' | '}
#Function to translate string to morse code
def translate(data):
text = data.lower()
#guardian code
count = 0
for i in text:
print morse_code[text[count]] + ' ',
count += 1
to_translate = raw_input("Type in the text that you would like
to translate into Morse code. ")
translate(to_translate)
March 24th, 2008 at 6:24 pm
this is looking good. One thing though: why are you using the count variable? You see, the for loop iterates over the elements in an iterator. In your case, you are iterating over text. So, each iteration of the loop, the variable i (it is actually a variable) will contain next character of the text.
allow me to demonstrate in the python interpreter:
>>> for i in “abcdefgh”:
… print i
…
a
b
c
d
e
f
g
h
>>>
of course, it makes more sense to name the variable something like char instead of i. The name is completely arbitrary. The point is, that i is there for a reason. The for loop should be read as such (pseudo code):
for (each) item in iterator:do_stuff_with(item)
in other words, your code doesn’t need a count variable to find the next character in the text. The variable i already contains the character:
for i in text:print morse_code[i]
March 26th, 2008 at 10:05 am
Aha!! I see exactly what you mean. That’s the stuff that I seem to be missing when I code. Most of my code works, just not in the most efficient, elegant, or intelligent way.
Awesome advice, thank you Yoshi. I’m going to repost this.
March 27th, 2008 at 9:33 am
You hae both the “A” and “W” characters as “.–” - “a” is “.-”
March 27th, 2008 at 9:39 am
Thanks Fred. I made the changes. Nice eye.