Boolean function on variable-length lists

Jussi Piitulainen jpiitula at ling.helsinki.fi
Wed Sep 12 09:02:44 EDT 2012


Libra writes:

> 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.
> 
> 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
> 
> In this case, the function returns 0 because the third constraint is
> not satisfied.

So you would associate each constraint with an index. You could
maintain a list of constraints and apply it to the values as follows:

>>> cs = [ lambda x : x >= 1, lambda x : x <= 3, lambda x : x == 2,
...        lambda x : x >= 3 ]
>>> { f(x) for f, x in zip(cs, [1,2,3,4]) }
{False, True}
>>> { f(x) for f, x in zip(cs, [1,2,2,4]) }
{True}
>>> 

Then map the return value to 0 if it contains a False, else to 1.



More information about the Python-list mailing list