Python Forum

Full Version: How to fix bugs in Morse alphabet code?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
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 -.- / .- // -… ///


But in output I see:

Traceback (most recent call last):
File "C:/Users/dokipo/Desktop/pythonprojects/alphabet.py", line 29, in <module>
print(decode(encode("This is first testing sentence.")))
File "C:/Users/dokipo/Desktop/pythonprojects/alphabet.py", line 21, in <module>
morse_array = morse_text.split("/")
builtins.NameError: name 'morse_text' is not defined


Do you know how to debug this code? I need to let it in this form generally but improve bugs.
Thank you

import string

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", "-----")])

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")) # -.-/.-//-...///
Your function reads the data not into morse_text but into mroz_text. Probably a typo?

def decode(mroz_text: str) -> str:
    morse_array = morse_text.split("/")
(Oct-25-2021, 09:10 PM)bowlofred Wrote: [ -> ]Your function reads the data not into morse_text but into mroz_text. Probably a typo?

def decode(mroz_text: str) -> str:
    morse_array = morse_text.split("/")

Yes, and I also changed plaintext to plain_text but now i have there


Traceback (most recent call last):
File "C:/Users/dokipo/Desktop/pythonprojects/alphabet.py", line 29, in <module>
print(decode(encode("This is first testing sentence.")))
File "C:/Users/dokipo/Desktop/pythonprojects/alphabet.py", line 25, in <module>
plain_text += morse[current_element]
builtins.KeyError: 't'


What´s wrong with "t"?
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")) # -.-/.-//-...///
Output:
t/h/i/s/ /i/s/ /f/i/r/s/t/ /t/e/s/t/i/n/g/ /s/e/n/t/e/n/c/e/./// this is first testing sentence. this is second testing sentence. this is third testing sentence. k/a/ /b///
KeyError means that you tried to reference a key from a dictionary that didn't exist.

In this case it means that morse didn't have a key of "t" at the time you referenced it. You create it as an empty dictionary, but never seem to change it afterward. Is it necessary? Is it supposed to be translation_dict?
(Oct-25-2021, 09:31 PM)Axel_Erfurt Wrote: [ -> ]
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")) # -.-/.-//-...///
Output:
t/h/i/s/ /i/s/ /f/i/r/s/t/ /t/e/s/t/i/n/g/ /s/e/n/t/e/n/c/e/./// this is first testing sentence. this is second testing sentence. this is third testing sentence. k/a/ /b///

Thank you, but it doesn´t encode it to values in dictionary. By encoding I mean replacement of letters with several characters associated with them.
The error is saying it tried to lookup "t" in a dictionary and failed. The line where this happened is:
plain_text += morse[current_element]
If you look at your code morse only appears in these lines:
morse = {}
        plain_text += morse[current_element]
morse doesn't have any items at all. That is why it crashes when trying to lookup "t".

You should review the code that involves "alphabet". I added a line to print the dictionary.
for key, value in translation_dict.items():
    alphabet[key] = key
    alphabet[value] = value
print(alphabet)
And I don't think "alphabet" contains what you think it does. A sample...
Output:
{'a': 'a', '.-': '.-', 'b': 'b', '-...': '-...', 'c': 'c', '-.-
So alphabet['a'] == 'a', not '.-' and alphabet['.-'] == '.-', not 'a'. It you use this dictionary to translate it would convert "This" to "this".

What is "alphabet" supposed to be? Is it a letter->morse translation dictionary or a dictionary that contains letter->morse and morse->letter? If the former, you already have a letter->morse dictionary; translation_dict.
(Oct-26-2021, 01:46 PM)deanhystad Wrote: [ -> ]The error is saying it tried to lookup "t" in a dictionary and failed. The line where this happened is:
plain_text += morse[current_element]
If you look at your code morse only appears in these lines:
morse = {}
        plain_text += morse[current_element]
morse doesn't have any items at all. That is why it crashes when trying to lookup "t".

You should review the code that involves "alphabet". I added a line to print the dictionary.
for key, value in translation_dict.items():
    alphabet[key] = key
    alphabet[value] = value
print(alphabet)
And I don't think "alphabet" contains what you think it does. A sample...
Output:
{'a': 'a', '.-': '.-', 'b': 'b', '-...': '-...', 'c': 'c', '-.-
What is "alphabet" supposed to be? Since it is used in "encode()" I suspect it should be a dictionary of Morse codes for all the letters and numbers. But you already have a dictionary for that; translation_dict. What you don't have is a reverse dictionary for looking up the letter for a Morse code.
So you have a translation dictionary "alphabet" that cannot do translation, and your try to do translation with a dictionary that is empty.

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...
Is that better?

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


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:
        for key, value in alphabet.items():
            if value == val:
                plain_text += key
    return plain_text



print(encode("This is first testing sentence."))
print(decode(encode("This is first testing sentence.")))

print(encode("ka b")) # -.-/.-//-...///
Output:
-/..../../...//../...//..-./../.-./.../-//-/./.../-/../-./--.//..././-./-/./-./-.-././.-.-.-/// this is first testing sentence. -.-/.-//-...///
(Oct-26-2021, 03:16 PM)Axel_Erfurt Wrote: [ -> ]Is that better?

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


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:
        for key, value in alphabet.items():
            if value == val:
                plain_text += key
    return plain_text



print(encode("This is first testing sentence."))
print(decode(encode("This is first testing sentence.")))

print(encode("ka b")) # -.-/.-//-...///
Output:
-/..../../...//../...//..-./../.-./.../-//-/./.../-/../-./--.//..././-./-/./-./-.-././.-.-.-/// this is first testing sentence. -.-/.-//-...///

Yes, thank you
Pages: 1 2