Last active
July 31, 2020 22:15
-
-
Save phenotypic/2955583a6049383e1c2ee96717561171 to your computer and use it in GitHub Desktop.
Simple encoder/decoder for DNA and UTF-8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dnaBin = {'A': '00', 'T': '01', 'C': '10', 'G': '11'} | |
def selectionMenu(): | |
response = input('\nWould you like to encode or decode DNA? [e/D]: ').lower() | |
if response == 'e': | |
text = input('\nInput text to encode: ') | |
encodeDNA(text) | |
elif response == 'd': | |
text = input('\nInput DNA to decode: ') | |
decodeDNA(text) | |
else: | |
print('Invalid choice, please try again') | |
selectionMenu() | |
def encodeDNA(text): | |
text = bin(int.from_bytes(text.encode('utf-8', 'surrogatepass'), 'big'))[2:] | |
text = text.zfill(8 * ((len(text) + 7) // 8)) | |
sequence = '' | |
for i, x in enumerate(text): | |
if i % 2 == 0: | |
sequence += list(dnaBin.keys())[list(dnaBin.values()).index(x + text[i + 1])] | |
print('\nEncoded:', sequence) | |
def decodeDNA(text): | |
binary = '' | |
for c in text: | |
binary += dnaBin[c] | |
binary = int(binary, 2) | |
binary = binary.to_bytes((binary.bit_length() + 7) // 8, 'big').decode('utf-8', 'surrogatepass') or '\0' | |
print('\nDecoded:', binary) | |
selectionMenu() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment