Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use: while not in

I'm trying to check if a list has no member as boolean operator AND, OR, NOT.

I use:

while ('AND' and 'OR' and 'NOT') not in list:
  print 'No boolean operator'

However, when my input is: a1 c2 OR c3 AND, it prints 'No boolean operator', which means this list is considered no boolean operator in it by using above loop sentence.

Hope somebody can help to correct.

Thanks, Cindy

like image 628
CindyRabbit Avatar asked Feb 05 '11 18:02

CindyRabbit


People also ask

What is the difference between while and while not in Python?

There is little difference, other than bad style. and if while not pair: did not work, then you have probably been assigning other values to it that are truthy but are not equal to False . If pair is a boolean, and you want to continue while pair is false then while not pair should work.

What is a while not loop?

A WhileNotDoneLoop is a while loop in which the loop-control variable is a boolean, typically named done, which is set to true somewhere in the body of the loop. This is a CodeSmell that may indicate the designer didn't understand the purpose of the loop or didn't understand what the exit condition is.

Can we use while inside else?

While loop with else Same as with for loops, while loops can also have an optional else block. The else part is executed if the condition in the while loop evaluates to False . The while loop can be terminated with a break statement. In such cases, the else part is ignored.


3 Answers

The expression 'AND' and 'OR' and 'NOT' always evaluates to 'NOT', so you are effectively doing

while 'NOT' not in some_list:
    print 'No boolean operator'

You can either check separately for all of them

while ('AND' not in some_list and 
       'OR' not in some_list and 
       'NOT' not in some_list):
    # whatever

or use sets

s = set(["AND", "OR", "NOT"])
while not s.intersection(some_list):
    # whatever
like image 164
Sven Marnach Avatar answered Sep 28 '22 06:09

Sven Marnach


Using sets will be screaming fast if you have any volume of data

If you are willing to use sets, you have the isdisjoint() method which will check to see if the intersection between your operator list and your other list is empty.

MyOper = set(['AND', 'OR', 'NOT'])
MyList = set(['c1', 'c2', 'NOT', 'c3'])

while not MyList.isdisjoint(MyOper):
    print "No boolean Operator"

http://docs.python.org/library/stdtypes.html#set.isdisjoint

like image 26
gahooa Avatar answered Sep 28 '22 06:09

gahooa


anding strings does not do what you think it does - use any to check if any of the strings are in the list:

while not any(word in list_of_words for word in ['AND', 'OR', 'NOT']):
    print 'No boolean'

Also, if you want a simple check, an if might be better suited than a while...

like image 43
etarion Avatar answered Sep 28 '22 06:09

etarion