Boolean function on variable-length lists
Tim Chase
python.list at tim.thechases.com
Wed Sep 12 09:18:59 EDT 2012
On 09/12/12 08:02, Jussi Piitulainen wrote:
> Libra writes:
>> 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
>
> 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 ]
This can even be decoupled a bit more for dynamic creation:
>>> lst = [1,2,3,4]
>>> import operator as o
>>> conditions = [
... (o.ge, 1),
... (o.le, 3),
... (o.eq, 2),
... (o.ge, 3),
... ]
>>> [op(v, constraint) for ((op, constraint), v) in zip(conditions,
lst)]
[True, True, False, True]
>>> all(compare(value, constraint) for ((compare, constraint),
value) in zip(conditions, lst))
False
Note that you'd also want to check len(conditions)==len(lst) for
obvious reasons. :-)
-tkc
More information about the Python-list
mailing list