Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

My python solution to the MorseCode test #16

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 153 additions & 0 deletions MorseCode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
"""
Define exception raised when invalid morse code encountered
"""
class InvalidMorseCode(Exception):
pass

"""
Define MorseCode class which translates morse code to text
"""
class MorseCode():
"""
define a static dictionary that contains the letters of the alphabet as the
key and the morse code as the value
"""
translate_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' : '--..',
'0' : '-----',
'1' : '.----',
'2' : '..---',
'3' : '...--',
'4' : '....-',
'5' : '.....',
'6' : '-....',
'7' : '--...',
'8' : '---..',
'9' : '----.'
}

"""
generate a dictionary where the morse code is key and the value is the
letter. This makes it easier to translate the morse code.
"""
morse_to_letter_dict = {code:letter for letter, code in \
translate_dict.items()}

"""
Define init function for MorseCode class. Optional argument input sets
the morsecode to be translated to a default value
"""
def __init__(self, input = "-..||---||--."):
self.morsecode = input

"""
Define translate function which takes as input the morse code and returns
the translation.
"""
def translate(self, input=None):

if input != None:
self.morsecode = input

#create a list of morse code elements to be translated
codes = self.morsecode.split('||')
#print(codes)
translated = ''

for code in codes:
# check to see if we have a valid morse code
if code in self.morse_to_letter_dict.keys():
#append the letter corresponding to the morse code to the
#translation
translated += self.morse_to_letter_dict[code]
elif code == '':
#if we encounter an empty code then translate to a space
translated += ' '
else:
#print an error if we encounter an invalid code
#print("ERROR: code not found!")
raise InvalidMorseCode

return translated

"""
Define method to set the morse code to be translated
"""
def set_morsecode(self, input):
self.morsecode = input

"""
Define method to get the morse code which is being translated
"""
def get_morsecode(self):
return self.morsecode

# define a main function which executes some tests on this module
def main():

# define a dictionary that contains morse code with expected translation
test_dict = {
'-..||---||--.' : 'dog',
'....||.||.-..||.-..||---||||.--||---||.-.||.-..||-..' : 'hello world',
'...||---||...' : 'sos'
}

morsecode1 = MorseCode()
try:
"""
translate each morse code in the test dictionary and verify that the
MorseCode class returns the correct translation
"""
for morse, word in test_dict.items():
correct = "Correctly translated {morse} into {word}"
incorrect = """ERROR: Incorrectly translated {morse}.\r\n
Expected: {expected} but instead got {actual}"""
if morsecode1.translate(morse) != word:
print(incorrect.format(morse = morse, \
expected = word, \
actual = morsecode1.translate(morse)))
else:
print(correct.format(morse = morse, word = word))
except InvalidMorseCode:
print("ERROR: Invalid morse code exception raised!")

"""
Verify that the InvalidMorseCode exception is raised when an invalid
morse code sequence is provided
"""
try:
invalid_morse_code = '----'
morsecode1.translate(invalid_morse_code)
print("ERROR: invalid morse code exception not raised!")
except InvalidMorseCode:
print("Invalid morse code exception raised correctly")

# execute main function only if this code is run as a script
if __name__ == "__main__":
main()

4 changes: 4 additions & 0 deletions inputfile.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-..||---||--.
....||.||.-..||.-..||---||||.--||---||.-.||.-..||-..
...||---||...
....||..||.-.||.||||.-||-.||--.||.||.-..||---
21 changes: 21 additions & 0 deletions translatefile.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from MorseCode import MorseCode
from MorseCode import InvalidMorseCode
import re
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("file",help="input file with morse code to translate")
args = parser.parse_args()

morsecode1 = MorseCode()

with open(args.file, 'r') as input_file:
for line in input_file:
#strip out CR and LF characters at start and end of strings
cleanline = line.strip()
try:
print(morsecode1.translate(cleanline))
except InvalidMorseCode:
print("Error: invalid morse code encountered!")