Optimising list comparison
Jim Dennis
jimd at vega.starshine.org
Mon Mar 18 03:29:23 EST 2002
In article <kttk8.6969$OP.215047 at stones>, Graham Ashton wrote:
> A friend of mine is using Python in a research project where he needs to
> compare each element of two vectors, such that comparing [a, b, c] and
> [d, e, f] would involve comparing a with d, b with e and c with f.
> The only possible values in either list are 0, 1 and -1. When comparing
> two values, if either value is set to -1 then both values are deemed to be
> equal. So we've got:
> 0 == 0
> 0 == -1
> 1 == 1
> 1 == -1
> 1 != 0
> What he wants to know is simply whether all the values in the two lists
> are "equal", in which case the comparison returns 1, otherwise it returns
> 0.
If I'm understanding you correctly then you should bel
able to just use:
map(lambda x,y: not (x+y == 1), a, b)
Let me go back through your "truth" table and fill it out
for all possible permutations:
a b r a+b a+b == 1
0 == 0 1 0 0
0 == -1 1 -1 0
0 != 1 0? 1 1
1 == 1 1 2 0
1 == -1 1 0 0
1 != 0 0 1 1
-1 == 0 1? -1 0
-1 == -1 1? -2 0
-1 == 1 1? 0 0
... the ? lines denote the ones that I've added, the r column is
the (apparentely) desired result --- the only case where you want
to return false (0) is if a or b are one AND the other is zero.
I observe that in either of those cases the sum of a+b will be
1 (0+1 or 1+0). More importantly I note that ALL other cases the
sum of a+b must NOT be 1 (4th column in my table). Finally I notice
that this is the inverse of the (apparently) desired results in the
third column. Thus the expression lambda x,y: not (a+b == 1) seems
to work.
But perhaps I misunderstand.
I didn't do *any* benchmarking of this. It's just the simplest
bit of code I could see that seems to match the desired table in
a functionesque way.
> ----cut----
> Cheers,
> Graham.
More information about the Python-list
mailing list