Skip to content

Instantly share code, notes, and snippets.

@costastf
Last active April 16, 2021 09:37
Show Gist options
  • Save costastf/7875423dc36f67c2b4fe2850734bb988 to your computer and use it in GitHub Desktop.
Save costastf/7875423dc36f67c2b4fe2850734bb988 to your computer and use it in GitHub Desktop.
Multi tap encoding and decoding
from copy import deepcopy
class InvalidMultiTap(Exception):
"""Input is invalid"""
class MultiTap:
mapping = {1: ['1'],
2: ['a', 'b', 'c', '2', 'A', 'B', 'C'],
3: ['d', 'e', 'f', '3', 'D', 'E', 'F'],
4: ['g', 'h', 'i', '4', 'G', 'H', 'I'],
5: ['j', 'k', 'l', '5', 'J', 'K', 'L'],
6: ['m', 'n', 'o', '6', 'M', 'N', 'O'],
7: ['p', 'q', 'r', 's', '7', 'P', 'Q', 'R', 'S'],
8: ['t', 'u', 'v', '8', 'T', 'U', 'V'],
9: ['w', 'x', 'y', 'z', '9', 'W', 'X', 'Y', 'Z'],
0: [' ']}
# for the extended characters there does not seem to be a standard, so i came up with mine
# and it follows the keyboard of my Mac pro line by line.
extended = ['`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '+', '=',
'{', '}', '[', ']', '|', '\\',
':', ';', '"', "'",
'<', ',', '>', '.', '?', '/']
def __init__(self, extended=False):
self._dialpad = deepcopy(self.mapping)
if extended:
self._dialpad[1].extend(self.extended)
@property
def dialpad(self):
return self._dialpad
def encode(self, text):
result = []
for character in list(text):
for index, character_set in self.dialpad.items():
if character in character_set:
result.append(str(index) * (character_set.index(character) + 1))
continue
return ' '.join(result)
def decode(self, text):
result = []
for character_group in text.split():
if len(set(character_group)) > 1:
raise InvalidMultiTap(f'{character_group} does not seem to be valid multi-tap encoding.')
try:
index = int(character_group[0])
result.append(self.dialpad[index][len(character_group) - 1])
except (ValueError, IndexError):
raise InvalidMultiTap(f'{character_group} does not seem to be valid multi-tap encoding.')
return ''.join(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment