Skip to content Skip to sidebar Skip to footer

Python: Chemical Elements Counter

I want to get the elements for a given mixture. For examples, for a mixsture of Air (O2 and N2) and Hexane (C6H14) given by the dict with their respectives mole numbers mix = {'O2'

Solution 1:

You can iterate over the mix dict while using a carefully-crafted regex to separate each element from its count.

import re
from collections import defaultdict

mix = {'O2': 1, 'N2': 3.76, 'C6H14': 0.01}
out = defaultdict(float)
regex = re.compile(r'([A-Z]+?)(\d+)?')

for formula, value in mix.items():
    for element, count in regex.findall(formula):
        count = int(count) if count else1# supporting elements with no count,# eg. O in H2O
        out[element] += count * value

print(out)

outputs

defaultdict(<class'float'>, {'O': 2.0, 'N': 7.52, 'C': 0.06, 'H': 0.14})

Post a Comment for "Python: Chemical Elements Counter"