Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate using dictionaries

Tags:

python

I'm just trying some code from workbooks and there are different exercises but I wanted to try one with a pre-existing message, I've gotten this far but I can't figure out how to complete it. How would I go about doing this?

alphabet = {"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": "--.."}

message = ".-- .... . .-. . / .- .-. . / -.-- --- ..-"

for key,val in alphabet.items():
    if message in alphabet:
        print(key)
like image 749
Peter Toole Avatar asked Nov 26 '17 16:11

Peter Toole


2 Answers

The fundamental problem here is that you need to split the message into separate parts that can be decoded separately.

A message is first separated by slashes (words), and then by spaces (characters). So we can use split() twice here to obtain the elements:

for word in message.split('/'):
    for character in word.strip().split():
        # ... decode the character

Now we thus need something to decode the character. But storing a dictionary with characters as keys does not make much sense: we want to decode the message, so here the dots and hyphens need to be the keys, not the alphabet characters.

We can build a new dictionary ourselves, or construct a new dictionary automatically:

decode_dict = {v: k for k, v in alphabet.items()}

So then we can use a lookup approach:

decode_dict = {v: k for k, v in alphabet.items()}

for word in message.split('/'):
    for character in word.strip().split():
        print(decode_dict[character])  # print the decoded character
    print(' ')  # print space after the word

Now we obtain the decoded message, but with every character on a separate line. We can however use str.join and generators to generate a string first:

' '.join(''.join(decode_dict[character] for character in word.strip().split())
         for word in message.split('/'))

The outcome then is the decoded string:

>>> ' '.join(''.join(decode_dict[character] for character in word.strip().split())
...          for word in message.split('/'))
'WHERE ARE YOU'
like image 102
Willem Van Onsem Avatar answered Oct 14 '22 13:10

Willem Van Onsem


You need to reverse your dictionary:

alphabet1 = {b:a for a, b in alphabet.items()} 
message = ".-- .... . .-. . / .- .-. . / -.-- --- ..-"
decoded_message = ''.join(alphabet1.get(i, ' ') for i in message.split())

Output:

'WHERE ARE YOU'
like image 41
Ajax1234 Avatar answered Oct 14 '22 14:10

Ajax1234