Skip to content

Instantly share code, notes, and snippets.

@jeffThompson
Last active March 15, 2018 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jeffThompson/7789284 to your computer and use it in GitHub Desktop.
Save jeffThompson/7789284 to your computer and use it in GitHub Desktop.
Python script to generate all the possible words that can be made from the periodic table.
'''
EVERY WORD IN THE PERIODIC TABLE
Jeff Thompson | 2013 | www.jeffreythompson.org
Takes as its input the abbreviations of the elements in the
periodic table and returns all possible words that can be
generated from that input*.
Idea occurred while sitting through a boring meeting in a
lecture hall, staring at a periodic table on the wall.
* Well, probably not every word, but many-to-most. The longest
word generated (because that's how the code in the docs works
and in order to prevent the program from running forever) will
be as long as the # of items in the list + 1. There are 118
elements at 343 total characters, so that is the longest possible
word that can be created.
REQUIRES:
+ Enchant and PyEnchant for spell checking
- first install Enchant using Homebrew
- then install PyEnchant from the prebuilt binary
'''
from itertools import chain, permutations
import enchant
elements = [] # list of all input elements
words = [] # output list of words
numPermutations = 0 # count the # of permutations created
dict = enchant.Dict('en_US') # load US English dictionary - change to try in other languages...
# POWERSET FUNCTION
# generates all permutations of all lengths, via Itertools docs
def powerset(iterable):
s = list(iterable)
return chain.from_iterable(permutations(s, r) for r in range(len(s)+1))
# LOAD ELEMENTS INTO LIST
with open('PeriodicTable.txt') as file:
for element in file:
elements.append(element.strip())
# ITERATE COMBINATIONS, CHECK AGAINST DICTIONARY
# this is where the magic happens :)
print '\n\n\nChecking all combinations...\n'
for perm in powerset(elements): # iterate the powerset
numPermutations += 1 # count permutations as we go
word = ''.join(perm) # convert tuple to string
if word != '' and dict.check(word.lower()): # check spelling (must be lowercase)
words.append(word) # if a word, add to list...
print '>> ' + word # ...and print the result
# WRITE RESULTING WORDS TO FILE
with open('PeriodicTableWords.txt', 'a') as file:
for word in words:
file.write(word + '\n')
# ALL DONE!
print '\n' + 'ALL DONE!'
print 'Created ' + str(len(words)) + ' words from ' + str(numPermutations) + ' permutations.'
print '\n\n\n\n\n\n'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment