Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Algorithm to encode any text in the optimal chemical symbols representation. Full article at
# import elements database
from periodic import elements
# Exclude last 6 new elements, which have 3 letters provisional names
# And parse everything into a tuples array
elements = [(element.symbol, for element in elements[:-6]]
def print_elements(elements_array):
"""Prints an array of elements with brackets, and prints fake elements as normal text"""
print ''.join(
'[' + element[0] + ']' if element[1] != 'fake' else element[0]
for element in elements_array
def encode_one(left):
Internal recursive function. Algorithm:
list options
for element in (elements + fake element made of first letter):
if string starts with element:
if element isn't fake or options is empty:
if string equals to element:
append element to options
for option in encode(string - element):
append [element] + option to options
return options
options = []
for element in elements + [(left[:1], 'fake')]:
if left.startswith(element[0].lower()):
if element[1] != 'fake' or options == []:
if len(left) == len(element[0]):
for option in encode_one(left[len(element[0]):]):
options.append([element] + option)
return options
def score(option):
"""Calculates score of an option"""
fakes = 0
shorts = 0
longs = 0
for pos in option:
if pos[1] == 'fake':
fakes += len(pos[0])
elif len(pos[0]) == 2:
longs += 1
shorts += 1
return shorts**2 + longs**2.5 - fakes**3
def sort_options(options):
"""Sorts the options based on the score function"""
options = [(score(option), option) for option in options]
return [option[1] for option in options]
def encode(string):
"""Returns all the valid options"""
return sort_options(encode_one(string.lower()))
def print_options(string):
for option in encode(string):
print_options('Hello world!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment