conditional expression sought
Dave K
dk123456789 at REMOVEhotmail.com
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 home.com> 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:
>
>falsies=[0,0.0,[],(),{},'',None]
>truies=[49,3.14,[1,2,3],(4,5,6),{7:8,9:10},'nonempty']
>
>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])
>
>A=[]
>from random import randint
>for i in range(3):
> A.append(bool(randint(0,1)))
>B=truies[0:3]
>demo(A,B)
>
>A=[False,False,False]
>B=falsies[0:3]
>demo(A,B)
>print "I would have liked this to be B[2] = ",B[2]
>
(snip)
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 :)
Dave
More information about the Python-list
mailing list