Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

all( generator ) returns True when it should return False

I want to check if a string contains all the keywords. I am using the Enthought Canopy distribution.

For example:

string  = 'I like roses but not violets'
key_words = ['roses', 'violets', 'tulips']

I've read that the all function would serve me well. When I use this function in the following way

if all( keys in string.lower().split() for keys in key_words):
    print True

Then True is returned.

I would expect False to be returned since tulips is not in string.lower().split().

How can I fix this?

like image 840
user3600497 Avatar asked May 12 '26 09:05

user3600497


1 Answers

You probably have a from numpy import * in your code. numpy's all method does not handle generators well.

[1]: string  = 'I like roses but not violets'

[2]: key_words = ['roses', 'violets', 'tulips']

[3]: if all( keys in string.lower().split() for keys in key_words):
         ...:         print True
         ...:

[4]: from numpy import *

[5]: if all( keys in string.lower().split() for keys in key_words):
        print True
         ...:
True

If the context is beyond your control, then you can use from __builtin__ import all to revert all to its default version in your file. However, the recommended method is to either do a selective or a qualified import of numpy.

like image 97
musically_ut Avatar answered May 14 '26 00:05

musically_ut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!