conditional expression sought

Dave K dk123456789 at
Fri Jan 30 23:51:57 CET 2004

On Fri, 30 Jan 2004 01:06:55 GMT in comp.lang.python, "Elaine Jackson"
<elainejackson7355 at> wrote:

>Sorry to take so long but I wasn't sure what a "unit test" was (the other guy's
>post clarified it). Tell me if this isn't what you're looking for:
>def demo(A,B):
>    print "If A is ",A
>    print "and B is ",B
>    print "then (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) = ",
>    print (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2])
>from random import randint
>for i in range(3):
>    A.append(bool(randint(0,1)))
>print "I would have liked this to be B[2] = ",B[2]

Do you mean that the expression should return the last element in B if
all elements in A are false? If all subexpressions before the last are
false, the whole conditional reduces to:
    A[-1] and B[-1]

So simply force (a copy of) A[-1] to always be true. Instead of
rewriting demo, I'll cheat by modifying the call:

>>> A=[False, False, False]
>>> B=[0, 0.0, []]
>>> demo(A[:-1]+[True], B)
If A is  [False, False, True]
and B is  [0, 0.0, []]
then (A[0] and B[0]) or (A[1] and B[1]) or (A[2] and B[2]) =  []
>>> print A
[False, False, False]

For complete generality, you should also consider the case where
len(A) != len(B). Truncate the longer list, or extend the shorter?
Does it matter which list is shorter? Or forget the whole mess and
raise an exception? There are lots of reasonable possibilities, but
they won't all lead to the same result for certain input values.
You're in charge of this project, you decide :)


More information about the Python-list mailing list