Skip to content

Instantly share code, notes, and snippets.

@0xff07
Created November 6, 2019 14:20
Show Gist options
  • Save 0xff07/48b43868d3306632e84cfdf15da2bec9 to your computer and use it in GitHub Desktop.
Save 0xff07/48b43868d3306632e84cfdf15da2bec9 to your computer and use it in GitHub Desktop.
Simple program to calculate molar mass of molecules with formulae without braces
ELEMENT_TABLE = {'C':12.011, 'O':15.999, 'H':1.008, 'N':14.007, 'Cl':35.45, 'Br':79.904, 'K':39.098, 'S':32.06}
def molar_mass(name, elements=ELEMENT_TABLE):
buf = ''
digit = ''
molar_mass = 0.0
for i in range(len(name)):
c = name[i]
nxt = ''
if not (i == len(name) - 1):
nxt = name[i + 1]
if nxt.isupper() or nxt == '':
if c.isupper():
buf += c
molar_mass += elements[buf]
buf = ''
elif c.islower():
buf += c
molar_mass += elements[buf]
buf = ''
elif c.isdigit():
digit += c
molar_mass += elements[buf] * int(digit)
buf = ''
digit = ''
elif nxt.islower():
if c.isupper():
buf += c
elif c.islower():
print("invalid expression : consecutive lower case letters.")
break
elif c.isdigit():
print("invalid expression : digit followed by lower case letter.")
break
elif nxt.isdigit():
if c.isupper():
buf += c
elif c.islower():
buf += c
elif c.isdigit():
digit += c
return molar_mass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment