Skip to content

Instantly share code, notes, and snippets.

@natecrow
Created May 16, 2017 00:36
Show Gist options
  • Save natecrow/28f96c7a1f87d446ddc8906b4a0c943b to your computer and use it in GitHub Desktop.
Save natecrow/28f96c7a1f87d446ddc8906b4a0c943b to your computer and use it in GitHub Desktop.
This Python script generates English words from input letters. Letters are input in as one word, e.g. "abc" for letters a, b, and c. A minimum length for the generated words is also taken as input. I wrote this script to solve levels in the game Word Cookies.
import enchant
import math
import sys
from itertools import permutations
# read in letters and constraints from the user
letters = input("Letters (no delimiters): ")
min_len = input("Min length of words: ")
# make sure user entered correct input types
if not letters.isalpha() or not min_len.isdigit():
print ("Input type did not match what the prompt asked for.")
sys.exit()
if len(letters) <= 2:
print ("You must enter more than two letters")
sys.exit()
# turn min length into an int
min_len = int(min_len)
# set up spell checker
dict = enchant.Dict("en_US")
# get permutations from the given letters and
# add it to list if it is an English word
words = list()
for i in range(min_len, len(letters) + 1):
for p in permutations(letters, i):
if dict.check(''.join(p)):
words.append(''.join(p))
# sort words alphabetically and by length
words.sort(key=str.lower)
words.sort(key=len)
# print the permuted words with each line containing words of the same length
cur_word_len = len(words[0])
num_of_inital_letters = 2
n = len(letters) - num_of_inital_letters
for word in words:
if len(word) != cur_word_len:
cur_word_len = len(word)
print()
print (word + '\t', end="")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment