Boolean function on variable-length lists

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Sep 12 09:11:41 EDT 2012


On Wed, 12 Sep 2012 05:48:09 -0700, Libra wrote:

> Hello,
> 
> I need to implement a function that returns 1 only if all the values in
> a list satisfy given constraints (at least one constraint for each
> element in the list), and zero otherwise.

What are the restrictions on the constraints themselves?

Could they be arbitrarily complicated?

"Item 2 must be an even number divisible by 17 and 39 with at least eight 
digits but no greater than four million, unless today is Tuesday, in 
which case it must be equal to six exactly."

I'm going to assume you have a list of functions which take a single 
argument and then return True if it meets the constraint and False if it 
doesn't. Using your examples later:

> For example, I may have a list L = [1, 2, 3, 4] and the following
> constraints: 
> L[0] >= 1
> L[1] <= 3
> L[2] == 2
> L[3] >= 3

constraints = [ 
    lambda x: x >= 1,
    lambda x: x <= 3,
    lambda x: x == 2,
    lambda x: x >= 3,
    ]

ought to handle any reasonable constraint.

Then use the zip() function to match up constraints with values, and 
all() to make sure they are all met.

Since this sounds like homework, I won't give you the exact solution. If 
you still can't solve it, come back with your attempt and we'll give you 
a bit more help.


-- 
Steven



More information about the Python-list mailing list