Reputation: 41
I have built a program that randomly generates 8 separate letters and assigns them into a list called ranlet
(short for random letters). It then imports a .txt file into a list called wordslist
. Both the random generation of letters and loading the file works fine, as I have tested these parts individually, but then I hit a snag.
The program then must compare the ranlet
list to the wordslist
list, append the matching words to a list called hits
and display the words in the hits
list
I tried this:
for each in wordslist:
if ranlet==char in wordslist:
hits.append(wordslist)
else:
print "No hits."
print hits
Sadly, this didn't work. I have many more variations on this, but all to no avail. I would really appreciate any help on the matter.
Upvotes: 4
Views: 4011
Reputation: 12448
If you are new at Python
, this may be an 'easy to understand' answer:
hits = []
for word in wordslist:
if word in ranlet and word not in hits:
hits.append(word)
print hits
Upvotes: 2
Reputation: 309959
I think you could benefit from set.intersection
here:
set_ranlet = set(ranlet)
for word in word_list:
intersection = set_ranlet.intersection(word)
if intersection:
print "word contains at least 1 character in ran_let",intersection
#The following is the same as `all( x in set_ranlet for x in word)`
#it is also the same as `len(intersection) == len(set_ranlet)` which might
# be faster, but less explicit.
if intersection == set_ranlet:
print "word contains all characters in ran_let"
Upvotes: 3