Reputation: 1382
I want to compare two vector. This vector represents two alternative:
def select_dominant(a,b):
comp=a>b
if(comp):
return a
elif(a<b):
return b
else:
return "indifferent"
a=[1,10,1]
b=[1,1,10]
print(select_dominant(a,b))
It's expected that a and b should be "indifferent" because a and b can't dominate each other. For values like a=[1,1,1] b=[1,1,2] there is no problem for this code because b dominated to a. Consequently, i want to get "indifferent" return from this function. How can i get?
Upvotes: 2
Views: 561
Reputation: 879481
It looks like you want to compare two lists elementwise. If all
the values in a
are greater than or equal to the corresponding values in b
, then
return a
, if less than or equal return b
, and otherwise return 'indifferent'
.
You can apply the >=
operator to each element of a
and b
like this:
In [247]: a = [1,10,1]
In [248]: b = [1,1,10]
In [249]: map(operator.ge, a, b)
Out[249]: [True, True, False]
And you can test if all the values are True
using all
:
In [250]: all(map(operator.ge, a, b))
Out[250]: False
Thus, if you define:
import operator
def select_dominant(a,b):
ge = all(map(operator.ge, a, b))
le = all(map(operator.le, a, b))
return a if ge else b if le else 'indifferent'
then
In [242]: select_dominant([1,1,1], [1,1,2])
Out[242]: [1, 1, 2]
In [243]: select_dominant([1,1,2], [1,1,1])
Out[243]: [1, 1, 2]
In [244]: select_dominant([1,10,1], [1,1,10])
Out[244]: 'indifferent'
The expression
a if ge else b if le else 'indifferent'
is a so-called conditional expression.
It is a short-hand way to generate the same value that this code would assign to value
:
if ge:
value = a
elif le:
value = b
else:
value = 'indifferent'
Upvotes: 4