How to improve code for Morse alphabet?

Hello I would like to encode text to the Morse alphabet.
I need to debug it to correct outputs for the last four lines of print.

The ones on lines 31, 32 and 33 are first encoded and then decoded, so output should be the same as in the code.
The output on line 34 should be -.- / .- // -… ///

import string

translation_dict = dict([('a', '.-'), ('b', '-...'), ('c', '-.-.'), ('d', '-..'), ('e', '.'), ('f', '..-.'), ('g', '--.'), ('h', '....'), ('i', '..'), ('j', '.---'), ('k', '-.-'), ('l', '.-..'), ('m', '--'), ('n', '-.'), ('o', '---'), ('p', '.--.'), ('q', '--.-'), ('r', '.-.'), ('s', '...'), ('u', '..-'), ('v', '...-'), ('w', '.--'), ('x', '-..-'), ('y', '-.--'), ('z', '--..'), (' ', ''), ('/', '-..-.'), ('-', '-....-'), ('.', '.-.-.-'), (',', '--..--'), (' ', ''), ("1", ".----"), ("2", "..---"), ("3", "...--"), ("4", "....-"), ("5", "....."), ("6", "-...."), ("7", "--..."), ("8", "---.."), ("9", "----."), ("0", "-----")])

alphabet = {}
morse = {}

for key, value in translation_dict.items():
    alphabet[key] = key
    alphabet[value] = value

def encode(plaintext: str) -> str:
    plaintext = plaintext.lower()
    morse_text = ""
    for char in plaintext:
        morse_text += alphabet[char] + "/"
    morse_text += "//"
    return morse_text

def decode(mroz_text: str) -> str:
    morse_array = morse_text.split("/")
    plain_text = ""
    for i in range(len(morse_array)):
        current_element = morse_array[i]
        plain_text += morse[current_element]
    plain_text = plain_text[:-5]
    return plain_text

print(decode(encode("This is first testing sentence.")))
print(decode(encode("This is second testing sentence.")))
print(decode(encode("This is third testing sentence.")))
print(encode("ka b")) # -.-/.-//-...///

But after code enterring there are some errors:

Traceback (most recent call last):

  • File “C:/Users/doki/Desktop/pythonprojects/alphabet.py”, line 29, in *
  • print(decode(encode(“This is first testing sentence.”)))*
  • File “C:/Users/doki/Desktop/pythonprojects/alphabet.py”, line 16, in *
  • morse_text += alphabet[char] + “/”*
    builtins.KeyError: ‘t’

What things would you improve?

Thank you

That error means there’s no key 't' in the alphabet dictionary.

Yes, thank´s, I add it. And do you know what to do with other bugs?

There are no other bugs.
The “traceback” shows you all the “traces” the program went through to get to the bug - so you read it from bottom to top.
First is the actual error-type, then the line where it happened (within the function), the file, then the previos executed line (where the function was called), the file for it, and so on… If you would be working with complex libraries and imports, the traceback could span several modules.

Also your alphabet is complete garbage, you got some spelling errors and never intialize “morse”.
Please review your code. If you fix there errors, it works out :wink:
Apart from the fact it’s loosing the final letter of the sentence when decoding. You might wanna check that.

I have this code now. But I need to input chars from dictionary, no only letters with char /.

:frowning_face:

import string
 
alphabet = {}
morse = {}
 
 
translation_dict = dict([('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", "-----")])
 
 
 
for key, value in translation_dict.items():
    alphabet[key] = key
    alphabet[value] = value
 
def encode(plaintext):
    morse_text = ""
    plaintext = plaintext.lower()
    for char in plaintext:
        morse_text += alphabet[char] + "/"
    morse_text += "//"
    return morse_text
 
def decode(mroz_text):
    plain_text = ""
    morse_array = mroz_text.split("/")
    for val in morse_array:
        plain_text += val
    return plain_text
 
 
print(encode("This is first testing sentence.")) # for testing
print(decode(encode("This is first testing sentence.")))
print(decode(encode("This is second testing sentence.")))
print(decode(encode("This is third testing sentence.")))
print(encode("ka b")) # -.-/.-//-...///

So what works and what doesn’t? Try to focus on single element at the time.

For example in the last line:
print(encode(“ka b”)) # -.-/.-//-…///
I need output like -.-/.-//-…///, no k/a/ /b///.

Yes, the working things are:
/ between every char.
/ / in place of space
and /// in the end of sentence

But general thing - replace letters to several chars isn´t working.
For exmaple ( a to .-)(or b to -…) and so on…

Thank you

Focus on replacing letters correctly then. Take a closer look at the parts of code that are responsible for that. Consider what part might be wrong exactly. Knowing that with specific input, you get something else than expected, try to pin-point where the issue could be.

At first I replace

alphabet[key] = value
alphabet[value] = key

next I writed

plain_text += alphabet[val]

instead

plain_text += val

So now output is

-/…/…/…//…/…//…-./…/.-./…/-//-/./…/-/…/-./–.//…/./-./-/./-./-.-././.-.-.-///
-/…/…/…//…/…//…-./…/.-./…/-//-/./…/-/…/-./–.//…/./-./-/./-./-.-././.-.-.-///
-…-his is s.-.-.-cond -…-.-.-.-s-…-ing s.-.-.-n-…-.-.-.-nc.-.-.-.
-…-his is -…-hird -…-.-.-.-s-…-ing s.-.-.-n-…-.-.-.-nc.-.-.-.
-.-/.-//-…///

It is good basis, I see that first two lines and the last one are encoded correctly.
But there is some problem in decoding, some chars are encrypted correctly but most of sentence not…

Full code now:


import string
 
alphabet = {}
morse = {}
 
 
translation_dict = dict([('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", "-----")])
 
 
 
for key, value in translation_dict.items():
    alphabet[key] = value
    alphabet[value] = key
#print(alphabet)
 
def encode(plaintext):
    morse_text = ""
    plaintext = plaintext.lower()
    for char in plaintext:
        morse_text += alphabet[char] + "/"
    morse_text += "//"
    return morse_text
 
def decode(mroz_text):
    plain_text = ""
    morse_array = mroz_text.split("/")
    for val in morse_array:
        plain_text += alphabet[val]
    return plain_text
 
 
print(encode("This is first testing sentence.")) # for testing
print(encode("This is first testing sentence."))
print(decode(encode("This is second testing sentence.")))
print(decode(encode("This is third testing sentence.")))
print(encode("ka b")) # -.-/.-//-...///

Using one alphabet for both encoding and decoding is screwing your result up since punctuation has an encoding as well.

1 Like

do not remvoe the code you are asking forhelp about please

You got both an “alphabet” dict and a “morse” dict - why not use both?