I have a set of N chemical compounds enumerated 1, 2,…, N. For each compound, I have the fraction of each of its constituents, “A”, “B”, and so on. Compounds can also contain other compounds, in which case the corresponding fraction is given. For instance, for N = 5, a sample set is
mixes = {
1: {
"A": 0.32,
"B": 0.12,
"C": 0.15,
2: 0.41
},
2: {
"C": 0.23,
"D": 0.12,
"E": 0.51,
4: 0.14
},
3: {
"A": 0.24,
"E": 0.76
},
4: {
"B": 0.13,
"F": 0.01,
"H": 0.86
},
5: {
"G": 0.1,
2: 0.4,
3: 0.5
}
}
I would like an algorithm that gives the net fraction of each constituent in every compoound, i.e.
mixes = {
1: {
"A": 0.32,
"B": 0.12 + 0.41 * 0.14 * 0.13,
"C": 0.15 + 0.41 * 0.23,
"D": 0.41 * 0.12,
"E": 0.41 * 0.51,
"F": 0.41 * 0.14 * 0.01,
"H": 0.41 * 0.14 * 0.86
},
2: {
"B": 0.14 * 0.13,
"C": 0.23,
"D": 0.12,
"E": 0.51,
"F": 0.14 * 0.01,
"H": 0.14 * 0.86
},
3: {
"A": 0.24,
"E": 0.76
},
4: {
"B": 0.13,
"F": 0.01,
"H": 0.86
},
5: {
"A": 0.5 * 0.24,
"G": 0.1,
"B": 0.4 * 0.14 * 0.13,
"C": 0.4 * 0.23,
"D": 0.4 * 0.12,
"E": 0.4 * 0.51 + 0.5 * 0.76,
"F": 0.4 * 0.14 * 0.01,
"H": 0.4 * 0.14 * 0.86
}
}
My current approach involves recursion, but I´d like to know if there´s a clever way to do this. Perhaps using a tree-like data structure may help?