Skip to content
Advertisement

How to use boolean on list correctly?

def check(A,B,a,b):
    return A >= a and B >= b

A = [500, 500, 500]
a = [20, 0, 0]
B = [5, 5, 5, 5]
b = [0, 10, 0, 0]

print(check(A, B, a, b))

(result True)

I want result become False if only one in list A or B have small value than a or b. In this code B[1] < b[1] (5 >= 10) result I expect is False but is output True

Advertisement

Answer

From official doc:

The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.


To get False in your example, you can use built-in all() to compare all values in arrays:

def check(A, B, a, b):
    return all(x >= y for x, y in zip(A, a)) and all(x >= y for x, y in zip(B, b))


A = [500, 500, 500]
a = [20, 0, 0]
B = [5, 5, 5, 5]
b = [0, 10, 0, 0]

print(check(A, B, a, b))

Prints:

False
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement