I have a specific kind of array which looks often like this:
JavaScript
x
2
1
[{3: 'Ca'}, {2: [{1: 'P'}, {4: 'O'}]}]
2
and I want to convert it to something like Ca3(PO4)2
. Could someone help me? I tried a lot of techniques, but the code gets always really messy. I do not know what am i doing wrong. I use python by the way.
P.S.: if anything’s wrong, tell me in the comments, I’m new here
I tried to loop through the array and define an empty string, and along the way add the things together. Looks like it’s not that effective after all. I didn’t manage to make it work, it was spitting non-sense.
Advertisement
Answer
maybe too simple solution, but it’s working. tested on python 3.10
JavaScript
1
13
13
1
def tree_array_to_chemical_formula(tree_array: list) -> str:
2
result = ""
3
4
for element in tree_array:
5
for key, value in element.items():
6
if type(value) == list:
7
result += "(" + tree_array_to_chemical_formula(value)
8
+ ")" + str(key)
9
else:
10
result += value + (str(key) if key > 1 else "")
11
12
return result
13