Last active
December 12, 2015 03:58
-
-
Save raphaelm/4710624 to your computer and use it in GitHub Desktop.
Checks whether it is possible to compose a given name out of chemical element symbols, like Caroline out of Carbon (C), Argon (Ar), Oxygen (O), Lithium (Li) and Neon (Ne).
This file contains hidden or 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
#!/usr/bin/env python | |
# | |
# elements.py | |
# | |
# Checks whether it is possible to compose a given name out of chemical | |
# element symbols, like Caroline out of Carbon (C), Argon (Ar), Oxygen (O) | |
# Lithium (Li) and Neon (Ne). | |
# | |
# The implementation consists of a simple backtracking algorithm. | |
# | |
# Usage: | |
# python elements.py [name] | |
import sys | |
ELEMENTS = [ | |
'H','He','Li','Be','B','C','N','O','F','Ne','Na','Mg','Al', | |
'Si','P','S','Cl','Ar','K','Ca','Sc','Ti','V','Cr','Mn','Fe', | |
'Co','Ni','Cu','Zn','Ga','Ge','As','Se','Br','Kr','Rb','Sr', | |
'Y','Zr','Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn','Sb', | |
'Te','I','Xe','Cs','Ba','Hf','Ta','W','Re','Os','Ir','Pt','Au', | |
'Hg','Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Rf','Db','Sg','Bh', | |
'Hs','Mt','Ds','Rg','Cn','Uut','Fl','Uup','Lv','Uus','Uuo','La', | |
'Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', | |
'Lu','Ac','Th','Pa','U','Np','Pu','Am','Cm','Bk','Cf','Es','Fm', | |
'Md','No','Lr' | |
] | |
def elements_iteration(tosearch, current): | |
if tosearch == '': | |
return current | |
for i in range(3,0,-1): | |
if tosearch[0:i].title() not in ELEMENTS: | |
continue | |
current.append(tosearch[0:i].title()) | |
step = elements_iteration(tosearch[i:], current) | |
if step: | |
return step | |
else: | |
current.remove(tosearch[0:i].title()) | |
def elements(search): | |
return elements_iteration(search, []) | |
if __name__ == '__main__': | |
print(elements(sys.argv[1])) |
This file contains hidden or 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
#!/usr/bin/env python3 | |
# | |
# namelist.py | |
# | |
# Does what elements.py does for a file, containing one name per line | |
# | |
# Usage: | |
# python namelist.py [filename] | |
import elements | |
import sys | |
total = 0 | |
success = 0 | |
f = open(sys.argv[1]) | |
for line in f: | |
res = elements.elements(line.strip()) | |
total += 1 | |
if res is not None: | |
print(res) | |
success += 1 | |
print("%d out of %d, %.02f%%" % (success, total, (100*success/total))) |
Author
raphaelm
commented
Feb 4, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment