for_some(), for_all()?

Michael Hoffman m.h.3.9.1.without.dots.at.cam.ac.uk at example.com
Wed Sep 22 13:17:23 EDT 2004


aurora wrote:

> However I bet reduce() does not exploit the short circuit logic. Also 
> it  is a little clumsy to create another list to pass into reduce. Is 
> there  some equivalent of
> 
>   for_some(test, lst)
> or
>   for_all(test, lst)?

There are some recipes for any() and all() in the itertools documents 
that do what you want:

http://www.python.org/doc/current/lib/itertools-example.html

 >>> import itertools, timeit, operator 

 >>> def any(seq, pred=bool):
...     "Returns True if pred(x) is True at least one element in the 
iterable"
...     return True in imap(pred, seq)
...
 >>> def equals_0(x): return x == 0
...
 >>> items = range(500000) 

 >>> timeit.Timer("reduce(operator.__or__, [equals_0(x) for x in 
items])", setup="from __main__ import operator, equals_0, items").timeit(3)
4.1040000915527344
 >>> #timeit.Timer("any(items, equals_0)", setup="from __main__ import 
itertools, any, equals_0, items").timeit(3)
...
 >>> timeit.Timer("any(items, equals_0)", setup="from __main__ import 
itertools, any, equals_0, items").timeit(3) # short-circuit
0.0
 >>> del items[0] 

 >>> timeit.Timer("any(items, equals_0)", setup="from __main__ import 
itertools, any, equals_0, items").timeit(3) # no short-circuit, still faster
1.6640000343322754
--
Michael Hoffman



More information about the Python-list mailing list