This week's challenge comes to us from Mae McAllister, from Bath, in the United Kingdom. As you may know, each chemical element can be represented by a one or two-letter symbol. Hydrogen is H, helium is He, and so on. McAllister points out that there are two commonly known elements whose names each can be spelled using three other element symbols. Name either one.
Looks easy, right? The vocabulary of element symbols (H, He, etc.) is a closed class, which makes things much easier. I'm not certain, but for now we'll assume that "commonly known elements" means the element names as they appear on the periodic table, which is also a closed class.
Let's break down the components we need here:
- element_dict: We'll need a dictionary like {"helium": "H", ... } in order to sure that we don't try to spell an element name using it's own symbol. We can also use this dictionary to derive these lists, S and N:
- S: the list of element symbols
- ['H', 'He', 'Li', 'Be', ... ]
- N: the list of element names
- ['hydrogen', 'helium', 'lithium', ... ]
- Note that the name must be spell-able with exactly 3 element symbols, meaning the name has between 3 and 6 letters (because symbols are 1 or 2 letters). This means we should remove any elements with a name longer than 6 letters.
- check_symbols(element_name): For the main loop of our script, we'll want to check each name in N with a function that takes an element name and determines whether it can be spelled from the vocabulary in S.
- We know that the solution uses exactly 3 element symbols to spell an element name, and that the symbols used are from other elements.
- For example, we can't solve by spelling xenon with Xe, No, N because Xe is the symbol for xenon.
- So we'll use python's itertools.permutations to get all permutations of three symbols, then for each element name we process, we can immediately toss any permutation that contains the element's own symbol by checking the element_dict
- Then we iterate through the subset of permutations for each element name. Each time we find a match, we'll replace the symbol substring with a matching number of underscores (1 or 2), and if we find a permutation of symbols that replaces all the letters in the name with underscores, we've found a solution.
- It's important we use permutations rather than combinations here, because some symbols may have overlapping letters, so the results of replacing all the substrings can differ depending on the order of the symbols.
You can find my Python implementation here, and I'll be back after the Thursday deadline to share my solution. Good luck!
March 30, 2024 Update
The Thursday deadline has passed, so here's my solution:
See you next week!
No comments:
Post a Comment