Some more food for thought. Note that get_word_list()
is meant to return a list
for this demo, not the earlier implemented generator. The one you have above is the one to use.
>>> from random import choice
>>> word = 'WIDGETS'
>>> words = get_word_list()
>>> sample = [choice(words) for _ in range(10)]
>>> test = []
>>> for w in sample:
... x = set(word) # reset x each iteration
... x.intersection_update(set(w)) # an in-place operation
... test.append((w, x))
...
...
>>> test
[
('CONCERT', {'T', 'E'}),
('PREPARE', {'E'}),
('WHEREAS', {'S', 'E', 'W'}),
('MYSTERY', {'S', 'T', 'E'}),
('LEADING', {'G', 'I', 'D', 'E'}),
('MYSTERY', {'S', 'T', 'E'}),
('MEASURE', {'S', 'E'}),
('TOTALLY', {'T'}),
('SOLDIER', {'S', 'I', 'D', 'E'}),
('TOURIST', {'S', 'I', 'T'})
]
>>>
the above is edited to fit the window
8.7. sets â Unordered collections of unique elements â Python 2.7.18 documentation
Thatâs for version 2. Version 3 is likely different to some degree. Still, the old code works in version 3.
It follows that aside from thinking of an optimized algorithm we have a filterable array (the test
list).
>>> [*filter(lambda x: len(x[1]) == 1, test)]
[('PREPARE', {'E'}), ('TOTALLY', {'T'})]
>>>
>>> result = [w[0] for w in [*filter(lambda x: len(x[1]) == 1, test)]]
>>> result
['PREPARE', 'TOTALLY']
>>>
On the entire word_list, words that have one letter matching our word:
>>> test = []
>>> for w in words:
... x = set(a)
... x.intersection_update(set(w))
... test.append((w, x))
...
...
>>> result = [w[0] for w in [*filter(lambda x: len(x[1]) == 1, test)]]
>>> result
[
'ABANDON', 'ACCOUNT', 'AFRICAN', 'ANALYZE', 'ANYBODY', 'ANYMORE',
'APPROVE', 'ARRIVAL', 'ATTRACT', 'BALANCE', 'BILLION', 'CAPABLE',
'CAREFUL', 'CHAMBER', 'CHANNEL', 'CLEARLY', 'COMFORT', 'COMMAND',
'COMPARE', 'COMPLEX', 'CONCERN', 'CONFIRM', 'CONTACT', 'CONTROL',
'COUNCIL', 'COUNTRY', 'CRUCIAL', 'ECONOMY', 'EMBRACE', 'ENHANCE',
'EQUALLY', 'EXAMPLE', 'EXPLORE', 'FACTORY', 'FACULTY', 'FINALLY',
'FOREVER', 'FUNERAL', 'HANDFUL', 'HELPFUL', 'HORIZON', 'INQUIRY',
'JOURNEY', 'LIBRARY', 'MILLION', 'NATURAL', 'NUCLEAR', 'OLYMPIC',
'OPINION', 'OVERALL', 'PAINFUL', 'PERFORM', 'PORTRAY', 'PREPARE',
'PRIMARY', 'PRIVACY', 'PROBLEM', 'PROGRAM', 'QUALIFY', 'QUICKLY',
'RECOVER', 'REPLACE', 'REVENUE', 'ROUGHLY', 'SCHOLAR', 'TOBACCO',
'TOTALLY', 'UNIFORM', 'UNKNOWN', 'UNUSUAL', 'USUALLY'
]
>>>
above edited to fit the window
One last pièce de rÊsistance:
>>> from random import choice
>>> word = 'WIDGETS'
>>> words = get_word_list()
>>> test = []
>>> for w in words:
... x = set(a)
... x.intersection_update(set(w))
... test.append((w, x))
...
...
>>> points = [*filter(lambda x: len(x[1]) == 1, test)]
>>> result = [w[0] for w in points if w[0].count(w[1].pop()) == 2]
>>> result
[
'BILLION', 'CONTACT', 'EMBRACE', 'ENHANCE', 'EXAMPLE', 'EXPLORE',
'FOREVER', 'INQUIRY', 'MILLION', 'OPINION', 'PREPARE', 'RECOVER',
'REPLACE', 'TOTALLY'
]
>>>