Search strings in list containing specific letters in random order
37,604
Solution 1
It would be easy using set()
:
wordlist = ['mississippi','miss','lake','que']
letters = set('aqk')
for word in wordlist:
if letters & set(word):
print word
Output:
lake
que
Note: The &
operator does an intersection between the two sets.
Solution 2
for item in wordlist:
for character in letters:
if character in item:
print item
break
Solution 3
Here goes your solution:
for item in wordlist:
b = False
for c in letters:
b = b | (item.find(c) != -1)
if b:
print item
Author by
Alex
My name is Alexander and I am 24 years old. I am a student at The University of Copenhagen.
Updated on April 09, 2020Comments
-
Alex about 4 years
I am writing a code in Python 2.7 in which I have defined a list of strings. I then want to search this list's elements for a set of letters. These letters must be in random order. i.e. search the list for every single letter from input. I have been google'ing around but i haven't found a solution.
Here's what i got:
wordlist = ['mississippi','miss','lake','que'] letters = str(aqk) for item in wordlist: if item.find(letters) != -1: print item
This is an example. Here the only output should be 'lake' and 'que' since these words contain 'a','q' and 'k'. How can I rewrite my code so that this will be done?
Thanks in advance!
Alex