Skip to content

Instantly share code, notes, and snippets.

@daxxog
Created November 17, 2021 15:53
If you use this in production you are stupid.
from functools import cache
from typing import List, Tuple
from string import ascii_uppercase
def generate_sub(start: str = 'Z') -> Tuple[str]:
_l: List[str] = list(ascii_uppercase)
start_index: int = _l.index(start)
_o_list: List[str] = list(_l)
for i in range(0, start_index):
_l.remove(_o_list[i])
_l.append(_o_list[i])
return tuple(_l)
class SubstitutionCipher:
def __init__(self, key: str = 'Z'):
self._ascii_uppercase: Tuple[str] = tuple(ascii_uppercase)
self._sub: Tuple[str] = generate_sub(key)
@cache
def _lookup_encode(self, _char: str) -> str:
return self._sub[self._ascii_uppercase.index(_char.capitalize())]
@cache
def _lookup_decode(self, _char: str) -> str:
return self._ascii_uppercase[self._sub.index(_char.capitalize())]
def encode(self, string: str) -> str:
return ''.join(tuple(map(lambda char: self._lookup_encode(char), string)))
def decode(self, string: str) -> str:
return ''.join(tuple(map(lambda char: self._lookup_decode(char), string)))
if __name__ == '__main__':
c = SubstitutionCipher('C')
print(c.encode('UWSP'))
print(c.decode('WYUR'))
d = SubstitutionCipher('D')
print(d.encode('DAVID'))
print(d.decode('GDYLG'))
k = SubstitutionCipher('K')
print(k.encode('DAVID'))
print(k.decode('NKFSN'))
p = SubstitutionCipher('P')
print(p.encode('DAVID'))
print(p.decode('SPKXS'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment