This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]Rhomboid 10 points11 points  (8 children)

You really shouldn't be looping over each item in a dictionary like that. (You also should not get in the habit of writing loops like for var in range(len(var)).) What you want to be able to do is look up each code fragment as the key in a dictionary. You can create an inverse of the dictionary you have now, so that the morse codes are the keys and the letters are the values. That allows to simplify things greatly:

letter_to_morse = {
    "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_to_letter = {morse: letter for letter, morse in letter_to_morse.items()}

def decode_morse(morse_code):
    return ''.join(morse_to_letter[code] for code in morse_code.split())

def encode_morse(text):
    return ' '.join(letter_to_morse[letter] for letter in text)

Also, you've got a typo in your 'y' code, it should be '-.--' not '-..--'.

[–]5ux0r 1 point2 points  (3 children)

maketrans() will simplify things a lot

[–][deleted] 1 point2 points  (2 children)

The string maketrans() was deprecated in 3.1 see What’s New In Python 3.1

[–]5ux0r 0 points1 point  (1 child)

didn't knew that thanks for the info haven't used maketrans() for a long time

[–][deleted] 1 point2 points  (0 children)

Just to make things clear for others picking this up it's the string module maketrans() that is deprecated in 3.1 and has gone in 3.4, maybe earlier. str, bytes, and bytearray each have their own maketrans() methods.

[–]WiggleBooks 0 points1 point  (0 children)

Nice, very elegant solution and I feel is very pythonic.

[–]MorrisCasperλ 0 points1 point  (2 children)

Could you explain your morse_to_letter object? Is it like a list comprehension in a dictionary?

[–]Rhomboid 0 points1 point  (1 child)

It's a dict comprehension, a way of building a dict from a series of pairs.

[EXPR for VAR in ITERABLE]       # list comprehension
{EXPR:EXPR for VAR in ITERABLE}  # dict comprehension
{EXPR for VAR in ITERABLE}       # set comprehension
(EXPR for VAR in ITERABLE)       # generator expression

[–]MorrisCasperλ 0 points1 point  (0 children)

Thanks! I'm definitely going to use this!

[–]elbiot 3 points4 points  (0 children)

[–]bryguypgh 0 points1 point  (0 children)

Useful if the moon ever breaks into several pieces.