Are there some a, b such that max(a, b) != max(b, a)?

Viewed 1128

In python 3.x, are there some a, b such that max(a, b) != max(b, a)?

a and b should be of a built-in python type and do not contain any conversion.

The type of a and b can be: num, float, bool, list, tuple ...

Example:

a = 1 # Correct
a = [1, 2] # Correct
a = float('nan') # Wrong
2 Answers

This satisfies all criteria:

>>> max(1.0, float("nan"))
1.0

>>> max(float("nan"), 1.0)
nan

This is because any comparisons other than != or is with float("nan") always return false.

More generally, we can have max(a, b) != max(b, a) when the type(s) of a, b do not provide a total order. As Daniel Mesejo points out, sets have this property as well. For sets < means 'strict subset', but with {1, 2} and {3, 4} neither is a strict subset of the other, so:

>>> max({1, 2}, {3, 4})
{1, 2}

>>> max({3, 4}, {1, 2})
{3, 4}

This one technically doesn't have max(a, b) != max(b, a) because 1 == True, but there's still an observable difference:

>>> max(True, 1)
True

>>> max(1, True)
1

According to the documentation, using max on sets produces undefined results:

Accordingly, sets are not appropriate arguments for functions which depend on total ordering (for example, min(), max(), and sorted() produce undefined results given a list of sets as inputs).

Here is an example,

a = {1, 2}
b = {2, 3}
print(max(b, a) != max(a, b))

Output

True
Related