conditional expression sought
Elaine Jackson
elainejackson7355 at home.com
Sat Jan 31 06:57:39 CET 2004
Thanks. I've got this straightened around in my head now. I just sortof
'panicked' when I saw a boolean literal where I didn't expect one to be (ie:
returned by the expression with the A's and B's when all the A's are False). I
realized later that that's what I should have expected, and that you could
always just add "...or undefined()" to such an expression, where
def undefined():
raise "undefined conditional expression"
This is all just part of my newbie efforts to assimilate the language. Anyway,
thanks again for your help.
Peace
"Dave K" <dk123456789 at REMOVEhotmail.com> wrote in message
news:ulnl10teov6ceq1q52laduq13d7u9edddd at 4ax.com...
 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 Pythonlist
mailing list