Boolean function on variable-length lists

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Sep 12 09:46:48 EDT 2012


On 12 September 2012 14:25, Libra <librarama at gmail.com> wrote:

> On Wednesday, September 12, 2012 3:11:42 PM UTC+2, Steven D'Aprano wrote:
> > On Wed, 12 Sep 2012 05:48:09 -0700, Libra wrote:
>
> > > 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."
>
> Generally the constraints are quite simple, like the one in my example.
> But I can also have 2 or more constraints for each value:
> L[0] >= 1
> L[0] <= 5
>

You can use:
   lambda x: 1 <= x and x <= 5
or
  lambda x: 1 <= x <= 5


> To complicate a little, what about constraints like:
> L[0] + L[2] >= 3


You could rewrite all your constraints as functions on the sequence of
values:
  lambda y: 1 <= y[0] <= 5
  lambda y: y[0] + y[2] >= 3

If all of your constraints are linear (like all of the ones you have shown)
then you can represent each one as a set of coefficients for a linear
projection of the list combined with a threshold value (if this last point
doesn't make sense then just ignore it).

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120912/88782acd/attachment.html>


More information about the Python-list mailing list