r/pythonhelp • • Nov 16 '20

Counting atoms with python

I wish to calculate partial charge in complex (im a chemist)

So my problem is that i have a list : ['H2O','OH','COOH'] for exemple

I need to know the number of occurrences of all atoms. So here 4 for H. My problem is that the number of occurrences is the number of occurrences of the letter describing the atom if no stoechiométric coefficient, and else the number of that coefficient, but the number could appear or not at any place except at position 0.

I don't see how can i make this with python and now i'm quite confused.

Do you have any tips for me?

Thanks for your help and time!

3 Upvotes

15 comments sorted by

View all comments

1

u/ace6807 Nov 16 '20

Can you give me a few more examples of possible lists and their expected outputs?

1

u/ace6807 Nov 16 '20

I think this should do it but I was hoping for some more test cases to check it.

from collections import Counter


atom_counter = Counter()

molecules = ['H2O','OH','COOH']
atom_stack = []

for molecule in molecules:
    for i, a in enumerate(molecule):
        if a.isalpha():
            if i < len(molecule) - 1 and molecule[i + 1].isnumeric():
                atom_stack.append((a, molecule[i + 1]))
            else:
                atom_stack.append((a, 1))

print(atom_stack)

for element_count in atom_stack:
    atom_counter[element_count[0]] += int(element_count[1])

print(atom_counter)

1

u/heirna Nov 16 '20

Thank you so much!

I'm going to test this,

More examples :

[H2O2, F, P2O3] -> H = 2, F=1, P=2, O=5

[C6H8O7, H2O, OH] -> C=6, H=11, O=9

By chance, i do not have to deal with double letter element like Al or Cu for now

2

u/ace6807 Nov 16 '20

Oh yeah this will for sure have a problem with double letter elements but we could add a lookup list super easily to resolve that