473,287 Members | 1,813 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

"and" and "or" on every item in a list

GHZ
Is this the best way to test every item in a list?
def alltrue(f,l):
return reduce(bool.__and__,map(f,l))

def onetrue(f,l):
return reduce(bool.__or__,map(f,l))
>>alltrue(lambda x:x>1,[1,2,3])
False
>>>
alltrue(lambda x:x>=1,[1,2,3])
True
>>>
Thanks

Oct 29 '07 #1
7 1824
On Oct 29, 3:57 pm, GHZ <geraint.willi...@gmail.comwrote:
Is this the best way to test every item in a list?

def alltrue(f,l):
return reduce(bool.__and__,map(f,l))

def onetrue(f,l):
return reduce(bool.__or__,map(f,l))
>alltrue(lambda x:x>1,[1,2,3])
False
>alltrue(lambda x:x>=1,[1,2,3])
True
In Py2.5, you can use the builtin any() and all() functions.

In Py2.4, use the recipes from the itertools module:

def all(seq, pred=None):
"Returns True if pred(x) is true for every element in the
iterable"
for elem in ifilterfalse(pred, seq):
return False
return True

def any(seq, pred=None):
"Returns True if pred(x) is true for at least one element in the
iterable"
for elem in ifilter(pred, seq):
return True
return False

def no(seq, pred=None):
"Returns True if pred(x) is false for every element in the
iterable"
for elem in ifilter(pred, seq):
return False
return True
Raymond

Oct 29 '07 #2
On Oct 29, 3:57 pm, GHZ <geraint.willi...@gmail.comwrote:
Is this the best way to test every item in a list?

def alltrue(f,l):
return reduce(bool.__and__,map(f,l))

def onetrue(f,l):
return reduce(bool.__or__,map(f,l))
>alltrue(lambda x:x>1,[1,2,3])
False
>alltrue(lambda x:x>=1,[1,2,3])
True

Thanks
If you are using python 2.5 the best way would be something like this:
>>all(x 1 for x in [1,2,3])
False
>>any(x 1 for x in [1,2,3])
True

If you are using an earlier version you are still discouraged from
using reduce in place of a more readable construct. In most cases list
comprehension is encouraged over map also.

If `all' and `any' aren't defined you can use something like the
following. One advantage of these over what you posted is that they
will return as soon as an exit condition is reached as opposed to
processing the entire list.
Expand|Select|Wrap|Line Numbers
  1. if not all:
  2. def all(seq):
  3. for val in seq:
  4. if not val:
  5. return False
  6. return True
  7.  
  8. if not any:
  9. def any(seq):
  10. for val in seq:
  11. if val:
  12. return True
  13. return False
  14.  
Matt

Oct 29 '07 #3
On Oct 29, 6:57 pm, GHZ <geraint.willi...@gmail.comwrote:
Is this the best way to test every item in a list?

def alltrue(f,l):
return reduce(bool.__and__,map(f,l))

def onetrue(f,l):
return reduce(bool.__or__,map(f,l))
Probably not, because it doesn't take advantage of short circuiting.
You could bail out of alltrue as soon as the first item you see is
false, but your version applies f to every item in the list. I would
suggest the most straightforear way is the best:

def alltrue(f,l):
for item in l:
if not f(item):
return False
return True
On Python 2.5, you could do this:

all(f(x) for x in l)
Carl Banks

Oct 29 '07 #4
On Oct 29, 10:57 pm, GHZ <geraint.willi...@gmail.comwrote:
Is this the best way to test every item in a list?

def alltrue(f,l):
return reduce(bool.__and__,map(f,l))

def onetrue(f,l):
return reduce(bool.__or__,map(f,l))
No. In Python 2.5 there are builtins 'all' and 'any' that do exactly
these. If you're using python <2.5, then you can support shortcut
evaluation - there's no need to check every element once you find a
false in 'all' or a true in 'any'.

--
Paul Hankin

Oct 29 '07 #5
Is this the best way to test every item in a list?
>
def alltrue(f,l):
return reduce(bool.__and__,map(f,l))

def onetrue(f,l):
return reduce(bool.__or__,map(f,l))
>>>alltrue(lambda x:x>1,[1,2,3])
False
>>>alltrue(lambda x:x>=1,[1,2,3])
True
As of Python2.5, there's an any() and all() function built into
the language.
>>any(map(lambda x: x>1, [1,2,3]))
all(map(lambda x: x>1, [1,2,3]))
Implementations for older versions are given at

http://docs.python.org/lib/built-in-funcs.html

You can adjust the "if" test in the example code so that it calls
your function...something like

def my_any(f, iterable):
for element in iterable:
if f(element):
return True
return False

def my_all(f, iterable):
for element in iterable:
if not f(element):
return False
return True

The advantage of the code in the docs is that it
short-circuits...there's no need to reduce the entire list if an
early item triggers the condition (a "true" early in an "any" or
a "false" early in an "all").

While you can use a reduce(bool.__and__, thing) call, I more
frequently see it as reduce(operator.or_, thing)

Just a few ideas,

-tkc

Oct 29 '07 #6
On Oct 29, 5:57 pm, GHZ <geraint.willi...@gmail.comwrote:
Is this the best way to test every item in a list?
No.

The biggest problem is, obviously, you don't take advantage of
builtins any() and all(), or write corresponding short-circuiting
versions for python versions before 2.5.

The second problem is you build an entire list that gets disposed of
just as quickly. The third problem is you use lambda, which makes your
call to map() time inefficient as well as space inefficient. Both of
these problems can be fixed by using generator expressions.
def alltrue(f,l):
return reduce(bool.__and__,map(f,l))

def onetrue(f,l):
return reduce(bool.__or__,map(f,l))
>alltrue(lambda x:x>1,[1,2,3])
False
>>all(x>1 for x in [1,2,3])
False
>alltrue(lambda x:x>=1,[1,2,3])
True
>>all(x>=1 for x in [1,2,3])
True
Thanks
HTH

Oct 30 '07 #7
GHZ
Thanks for the answers, I suspected something like any(), all()
existed. Also got me thinking about generator expressions, my code is
full of list comprehensions for lists I don't keep.

Oct 30 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: gcash | last post by:
I'm doing stuff using COM to automate IE, for some boring repetitive portal tasks I have to do. Anyway, every so often I'll make some sort of error and things will crash, and I'll have to do...
11
by: tdi | last post by:
Ok, stupid question for the day. I'm reading the interview with Steve Moret and he says: "Once a lot of scripts started going in we knew there was no way we could back out of using Python." I'm...
11
by: Ohaya | last post by:
Hi, I'm trying to understand a situation where ASP seems to be "blocking" of "queuing" requests. This is on a Win2K Advanced Server, with IIS5. I've seen some posts (e.g.,...
9
by: dover | last post by:
For the code, outputfile << *p << endl; Someone suggests: Don't use endl here; it is flushing output stream every time. Use plain '\n'. What's the difference of using "endl" and "\n" above?...
2
by: thomasfj | last post by:
Hi, Accroding to MS documentation the use of union and list elements in XSD simpleType (valid according to W3C standards) is valid used as an dataset schema...but it's not!! When loading the...
37
by: jht5945 | last post by:
For example I wrote a function: function Func() { // do something } we can call it like: var obj = new Func(); // call it as a constructor or var result = Func(); // call it as...
3
by: darnnnel | last post by:
I have a a statement as follows: sSQL = "SELECT * FROM QueryCases WHERE Weekday(QueryCases.StartDate) = 1 OR Weekday(QueryCases.StartDate) = 7 ORDER BY QueryCases.StartDate;" I would like to add...
6
by: Russ P. | last post by:
I've always appreciated Python's lack of requirement for a semi-colon at the end of each line. I also appreciate its rules for automatic line continuation. If a statement ends with a "+", for...
21
by: Sami | last post by:
string = "" or string = string.Empty? should is the proper way? Sami
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.