You can try the following solution. The user has to enter some letters and the program looks, whether those letters can be found at the beginning or end of a word.
with open('words.txt') as f:
wordlist = [line.strip().lower() for line in f]
from itertools import permutations
while True:
userinput = raw_input("Please enter your letters: ").lower()
# look up any combinations of letters
for letter_permutation in permutations(userinput):
s = ''.join(letter_permutation)
for word in wordlist:
if word.startswith(s) or word.endswith(s):
print "'%s' is part of %s" % (s, word)
if raw_input('Press q to exit, any key to continue... ').lower() == 'q':
break
For small length of userinput, you can also create a tuple with all permutations, but since its size would increase with the factorial of the length, I would suggest to use the solution above. But for the sake of showing cool python stuff. (Thanks to Jon Clements for advise to use str.startswith
or str.endswith
with tuples)
while True:
userinput = raw_input("Please enter your letters: ").lower()
# create a tuple with all combinations of letters
perms = tuple( ''.join(letter_permutation)
for letter_permutation in permutations(userinput) )
# now check if any of the words starts or ends with any of the letter-perms
for word in wordlist:
# startswith, endswith also take tuples as arguments
if word.startswith(perms) or word.endswith(perms):
print "'%s' can be found in %s" % (userinput, word)
if raw_input('Press q to exit, any key to continue... ').lower() == 'q':
break