Repository navigation
Expand file tree
/
Copy pathmorse_code.py
More file actions
51 lines (41 loc) · 1.66 KB
/
Copy pathmorse_code.py
File metadata and controls
51 lines (41 loc) · 1.66 KB
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
# @tremlab
# a python module that builds a populated binary tree for morse code values, with a method to easily translate a morse code string to its letter.
# from morse_code import Morse_Code_Bin_Tree
# mc_tree = Morse_Code_Bin_Tree()
# mc_tree.translate_mc_to_letter("....") => "H"
class Morse_Code_Bin_Tree(object):
"""Class that initializes and populates a binary tree for translating morse code strings into letters.
"""
def __init__(self):
self.head = Node("*")
letters = "ETIANMSURWDKGOHVF*L*PJBXCYZQ**54*3***2**+****16=/*****7***8*90"
current = self.head
nexts = []
for char in letters:
if current.left == None:
current.left = Node(char)
else:
if current.right == None:
current.right = Node(char)
else:
nexts.append(current.left)
nexts.append(current.right)
current = nexts.pop(0)
current.left = Node(char)
def translate_mc_to_letter(self, mc_ltr_str):
"""method that takes a string input of morse code, traverses the morse code binary tree, and returns the correct letter for that sequnce.
e.g. "...." => "H"
"""
current = self.head
for char in mc_ltr_str:
if char == ".":
current = current.left
else:
current = current.right
return current.val
class Node(object):
"""binary node"""
def __init__(self, char):
self.val = char
self.left = None
self.right = None