-
Notifications
You must be signed in to change notification settings - Fork 0
/
MorseTranslator.py
76 lines (68 loc) · 2.94 KB
/
MorseTranslator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""
Morse translator tool
"""
LETTERS_TO_MORSE_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' : '-----'}
MORSE_TO_LETTERS_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'}
def encode(to_encode):
"""
Morse encoder
"""
output = ''
for letter in to_encode:
try:
output += LETTERS_TO_MORSE_DICT[letter] + ' '
except KeyError:
output += ''
return output
def decode(to_decode):
"""
Morse decoder
"""
output = ''
current_sequence = ''
for letter in to_decode:
if letter == ' ':
try:
output += MORSE_TO_LETTERS_DICT[current_sequence]
except KeyError:
print 'Sequence {} does not exist in the dictionary'.format(current_sequence)
finally:
current_sequence = ''
continue
current_sequence += letter
try:
output += MORSE_TO_LETTERS_DICT[current_sequence]
except KeyError:
print 'Sequence {} does not exist in the dictionary'.format(current_sequence)
finally:
current_sequence = ''
return output
def main():
"""
Main function
"""
answer_type = raw_input('Would you like to encode or decode?\n').lower()
while True:
if answer_type == 'encode' or answer_type == 'decode':
break
else:
print '\n\nAnswer only encode or decode'
answer_type = raw_input('Would you like to encode or decode?\n').lower()
if answer_type == 'encode':
print encode(raw_input('\nWhat would you like to encode?\n'))
elif answer_type == 'decode':
print decode(raw_input('\nWhat would you like to decode?\n'))
if __name__ == "__main__":
main()