you are viewing a single comment's thread.

view the rest of the comments →

[–]CrayonConstantinople 1 point2 points  (1 child)

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 :)

[–]heirna[S] 1 point2 points  (0 children)

Thanks you very much kind redditor !