I am in my first year of programming with Python 3 and am wondering if anyone had a better way to program this problem. When the user provides up to 7 random letters as a single string, the program should read the ‘wordlist.txt’ file, list the words from that file that can be constructed using some or all of those letters.
For example, if the user provides three letters, ‘AER’ as a string, the program will suggest the following words from the given file: 'AE', 'AR', 'ARE', 'EA', 'EAR', 'ER', 'ERA', 'RE'
This is what I have for now:
wordlist=list(line.strip('\n') for line in open('wordlist.txt','r')) def wordFinder(): words= letters=str.upper(input('enter up to 7 letters:')) for word in wordlist: candidate=True letterlist=list(letters) for letter in word: if letter not in letterlist: candidate=False break else: letterlist.remove(letter) if candidate==True: words.append(word) return words >>>options() enter up to 7 letters:aer >>>['AE', 'AR', 'ARE', 'EA', 'EAR', 'ER', 'ERA', 'RE']
Even though it works I am looking to see if there is an easier/more efficient way for doing it. I came close with list comprehension, but I couldn't figure out how to avoid input letters matching more than once with the potential words.
def options2(): words= letters=set(str.upper(input('Enter up to 7 letters:'))) words=[w for w in wordlist if set(w).issubset(letters) and len(w)<=len(letters)] return words >>>options2() enter up to 7 letters:aer >>>['AA','AE','AR','ARE','EA','EAR','EE','ER','ERA','ERE','ERR','RE','REE']
If any changes could be made for the second function to work that would be awesome.