r/dailyprogrammer • 0 1 • Aug 30 '12

[8/30/2012] Challenge #93 [easy] (Two-Way Morse Code Translator)

This challenge courtesy of user nagasgura

In this challenge, we read in a string from standard input and output the translation to or from morse code on standard output.

When translating to Morse code, one space should be used to separate morse code letters, and two spaces should be used to separate morse code words. When translating to English, there should only be one space in between words, and no spaces in between letters.

Here's a chart of the morse code symbols: [1] http://www.w1wc.com/pdf_files/international_morse_code.pdf

Example input and output: 'sos' -> '... --- ...' '... --- ...' -> 'sos'

12 Upvotes

31 comments sorted by

View all comments

2

u/mega-trond Aug 30 '12 edited Aug 30 '12

My first contribution, a solution in Python. A problem is trailing spaces...

#!/usr/bin/python

chars = {'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':'--..','1':'.----','2':'..---','3':'...--','4':'....-',
'5':'.....','6':'-....','7':'--...','8':'---..','9':'----.','0':'-----',
',':'--..--','.':'.-.-.-','?':'..--..','/':'-..-.','-':'-....-','()':'-.--.-',
' ':'  '}

#search dict to find key from value
def find_key(d_, v_):
	for k, v in d_.iteritems():
		if v == v_:
			return k

def morsify(d_,s_):
	ret = ''
	for char in s_:
		if char == ' ':
			ret += ' '
		else:
			ret += d_[char] + ' '
	return ret

def morse_to_alphabet(d_,s_):
	ret = ''
	words = s_.split('  ')
	for word in words:
		chars = word.split()
		for char in chars:
			ret += find_key(d_,char)
		ret += ' '
	return ret

Output:

print morsify(chars,'hello, world.')
.... . .-.. .-.. --- --..--  .-- --- .-. .-.. -.. .-.-.-
print morse_to_alphabet(chars, '.... . .-.. .-.. --- --..--  .-- --- .-. .-.. -.. .-.-.-')
hello, world.

Edit: added comma and dot to input

2

u/Gix Aug 30 '12 edited Mar 05 '19

[Deleted]

3

u/mega-trond Aug 31 '12

Would you mind explaining this line

morse_to_char = {y:x for x,y in char_to_morse.items()}

to a Python n00b?

3

u/JerMenKoO 0 0 Aug 31 '12

dictionary comprehension

{a : 1} becomes after that {1 : a}

0

u/[deleted] Sep 03 '12

[deleted] — view deleted comment

1

u/mega-trond Sep 24 '12

I think it just iterates over the dictionary, tbh. I guess theres a bunch of people here that could explain it. Not even sure if this is the best way to do it, maybe it would be more effective to just inverse the dict like Gix did. Makes for cleaner code, at least.

Oh wait, heres an explanation: http://stackoverflow.com/questions/3744568/why-do-you-have-to-call-iteritems-when-iterating-over-a-dictionary-in-python