#!/usr/bin/env python3 # Function to print words which can be created using a given set of characters # Inspired by https://www.geeksforgeeks.org/possible-words-using-given-characters-python/ # Improved for use in an online puzzle by me! # CHANGE 2020-0415: Added click for argument handling, added comments. import click def possible_words(lwords, charSet): ## Build and return a list of good words ## by iterating through every possible word ## and adding it to the list if all of its characters ## are in the character set. good_words = [] for word in lwords: word_chars_in_charSet = [(char in charSet) for char in word] if all(word_chars_in_charSet): good_words.append(word) return good_words @click.command() @click.argument('characters', required=False) def find_words(characters): # if puzzle characters not passed via argument, # prompt for them, and then split into list of characters. if not characters: characters = click.prompt('Please enter characters from the puzzle, center character first') charSet = [letter for letter in characters] # Find all possible words from the nltk english corpus using the characters, from nltk.corpus import words pwords = possible_words(words.words(), charSet) # filter the list to only words containing the first (center) character and sort the list. filtered_list = sorted([word for word in pwords if len(word) >= 4 and charSet[0] in word]) # Print the list with a navigation index, and highlights for long (high value) words. for i in range(len(filtered_list)): print(i,filtered_list[i],'*' if len(filtered_list[i]) >= 7 else '') if __name__ == "__main__": find_words()