A and B but not C in list
Arnaud Delobelle
arnodel at gmail.com
Wed Jan 26 03:10:23 EST 2011
More information about the Python-list mailing list
Wed Jan 26 03:10:23 EST 2011
- Previous message (by thread): A and B but not C in list
- Next message (by thread): A and B but not C in list
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Terry Reedy <tjreedy at udel.edu> writes: > On 1/23/2011 4:05 PM, CM wrote: >> In Python, is there a recommended way to write conditionals of the >> form: >> >> "if A and B but not C or D in my list, do something." ? >> >> I may also have variations on this, like "if A but not B, C, or D". >> >> Do I have to just write out all the if and elifs with all possible >> conditions, or is there a handier and more code-maintainable way to >> deal with this? > > The straightforward code > > if a in L and b in L and c not in L and d not in L > > scans the list 4 times. One scan be be done generically as follows: > > def req_pro(iterable, required = set(), prohibited = set()): > for item in iterable: > if item in prohibited: > return False > elif item in required: > required.remove(item) > else: > return not required # should now be empty > > if req_pro(my_list, {A,B}, {C,D}): ... > # untested, of course.. But what's better? Four fast list scans or one slow one? -- Arnaud
- Previous message (by thread): A and B but not C in list
- Next message (by thread): A and B but not C in list
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list