Skip to content
Advertisement

converting a tree array to a specific string (chemical formulas) (py)

I have a specific kind of array which looks often like this:

[{3: 'Ca'}, {2: [{1: 'P'}, {4: 'O'}]}]

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

def tree_array_to_chemical_formula(tree_array: list) -> str:
    result = ""

    for element in tree_array:
        for key, value in element.items():
            if type(value) == list:
                result += "(" + tree_array_to_chemical_formula(value) 
                          + ")" + str(key)
            else:
                result += value + (str(key) if key > 1 else "")

    return result
Advertisement