# Calculating reaction products programmatically?

I was wondering if there was a known algorithm which could calculate simple reaction products - not anything organic, but things like

$$\ce{NaBr + LiF -> NaF + LiBr}$$

While these are quite easily to be worked out mentally, I cannot think of an easy way in which these reaction products could be predicted. Is there some software which does this (most I have found simply uses databases of known reactions), or even better an algorithm which does it?

You are looking at the most simple form of double displacement reactions of salts with

$\ce{M^1X^1 + M^2X^2 -> M^1X^2 + M^2X^1}$

Dissolving these salts leads to complete dissociation $\ce{MX -> M+ + X-}$. From the solution, pairs of anions and cations recombine.

1. Using a lookup table with elements, you could identify the cation from each string that represents a starting material (=salt). The remaining string is the anion.

2. Build three lists:

• a list of cations cations = ['Na', 'Li']
• a list of anions anions = ['Br', 'F']
• a list of the starting materials
3. With Python, itertools.product(cations, anions) will give a generator object that yields tuples of all possible cation-anion combinations

4. These tuples can be joined to strings for a possible salts
5. Put these strings in a list and subtract the list of the starting materials to obtain the possible products
import itertools as it
reactants = ['NaBr', 'LiF']
# splitting the string via lookup table is something I leave up to you
cations = ['Na', 'Li']
anions = ['Br', 'F']

pr = it.product(cations, anions)
pairs = list(pr)
# yields list of tuples [('Na', 'F'), ('Na', Br'), ...]

salts = [''.join(pair) for pair in pairs]
# yields a list of strings by joining the tuples:
# ['NaBr', 'NaF', 'LiBr', 'LiF']

products = [salt for salt in salts if not salt in reactants]
# only gives those salts that are not in the list of reactants

• @Mithoron Yes, it does :) And the code tends to look readable, rather than like two porcupines mating on the keyboard. At least, I hope that the snippet above did. But this is of course our very personal opinion. The same result certainly could have been achieved using Ruby or any other modern language I'm just not aware of. – Klaus-Dieter Warzecha Apr 21 '15 at 5:30

Well I do not have a software but can offer some info on this.

If it is a double replacement:

• A liquid, solid, or gas must form.

If it is a single replacement:

• Element replacing other element must be higher on the activity series.

If you really want to make sure if the reaction happens, just calculate the $\ce{\Delta G}$ for it. If it is (-) then it is spontaneous and the reaction is thermodynamically favorable.

This is how I usually remember it. Works for me.

But otherwise Klaus got you covered :)