Rafael Carmona
Rafael Carmona

Reputation: 61

if variable not in list == False returns empty list

I need to make a program that takes a given string of letters and returns all the words within a given list that can be made only with those letters. For this, I used two "for" loops, one for the words in the list and ones for the letters in each word.

Now, so as to obtain only the words that could be made with nothing but the given letters, I used the following method:

def combinacion_palabras(lista_palabras,letras):
    palabras_correctas = []
    letras_correctas = []
    for i in letras:
        letras_correctas.append(i)
    for p in lista_palabras:
        for c in p:
            if c not in letras_correctas == False:
                palabras_correctas.append(p)

    return palabras_correctas

Where lista_palabras is the list of the given words and letras is the string with the usable letters. I would expect this to return a list with all the words in lista_palabras that are made only of the letters inside the string letras, but instead it returns an empty list. What mistake am I making? Thanks in advance.

Upvotes: 1

Views: 169

Answers (2)

Hyperboreus
Hyperboreus

Reputation: 32429

Do you mean something like this?

def combinacion_palabras(lista_palabras, letras):
    return [palabra for palabra in lista_palabras if set(palabra) <= set(letras) ]

palabras = ['tomo', 'tomas', 'toma', 'tomamos', 'toman', 'mata']

print(combinacion_palabras (palabras, 'tom') )
print(combinacion_palabras (palabras, 'atoms') )
print(combinacion_palabras (palabras, 'tma') )

Or rather something like this?

def combinacion_palabras(list_palabras, letras):
    return [palabra for palabra in list_palabras if sorted(palabra) == sorted(letras) ]

palabras = ['tomo', 'tomas', 'toma', 'tomamos', 'toman', 'mata']

print(combinacion_palabras (palabras, 'otom') )
print(combinacion_palabras (palabras, 'atoms') )
print(combinacion_palabras (palabras, 'tama') )

Upvotes: 0

TerryA
TerryA

Reputation: 59974

Consider this example:

>>> L = ['a', 'b']
>>> 'a' not in L
False
>>> 'a' not in L == False
False
>>> ('a' not in L) == False
True

Order of precedence makes the L == False go first.

If you want to determine whether an item in the list, just do if c in letras_correctas:

Upvotes: 2

Related Questions