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

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.

a = ['H2O', 'OH', 'COOH']

def count_items(item_list):
  map = {}
  amount_of_char = None
  for item in item_list:
    for char in reversed(item):
      if char.isdigit():
        # This char is a number so keep for incrementing next letter
        if amount_of_char is None:
          amount_of_char = char
        else:
          amount_of_char = '{0}{1}'.format(char, amount_of_char)
      else:
        # Find the current count for this char, or 0 if there is none
        current_count = map.get(char.upper(), 0)
        # Determine the amount to increment this char by
        amount_to_increment = int(amount_of_char) if amount_of_char else 1
        map[char.upper()] = current_count + amount_to_increment
        amount_of_char = None
  return map

print(count_items(a))
# prints {'O': 4, 'H': 4, 'C': 1}
  • Edited to make the code easier to read :)

2

u/heirna Nov 16 '20

Thanks you very much kind redditor !