r/pythonhelp • u/heirna • 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
2
u/CrayonConstantinople Nov 16 '20 edited Nov 17 '20
This solves your problem but I had to write it on my tablet so excuse the fact that its just one function. It also could be written much nicer and explained etc.
But basically it goes through each item of the list.
For each item, it checks each letter from back to front.
If the letter is an actual letter (not a number), it increments that letters count by 1
If the letter is a number, it stores it and the next letter it comes across, it increments its by that count. This also works for multiple numbers. e.g. if it was H22, then the count for H would be 22.
Edited to make the code easier to read :)