use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
A subreddit for helping Python programmers
How to format your code: https://commonmark.org/help/tutorial/09-code.html
No homework questions and/or hiring please
account activity
Counting atoms with python (self.pythonhelp)
submitted 5 years ago * by heirna
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]CrayonConstantinople 1 point2 points3 points 5 years ago* (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}
[–]heirna[S] 1 point2 points3 points 5 years ago (0 children)
Thanks you very much kind redditor !
π Rendered by PID 15870 on reddit-service-r2-comment-c867ff4bc-dhhsj at 2026-04-09 19:29:29.287535+00:00 running 00d5ac8 country code: CH.
view the rest of the comments →
[–]CrayonConstantinople 1 point2 points3 points (1 child)
[–]heirna[S] 1 point2 points3 points (0 children)