Python: used values ​​of Max and Min

Python 2.x allows you to compare heterogeneous types.

A useful shortcut (in Python 2.7 here) is that None compared less than any integer or floating value:

 >>> None < float('-inf') < -sys.maxint * 2l < -sys.maxint True 

And in Python 2.7, an empty tuple () is an infinite value:

 >>> () > float('inf') > sys.maxint True 

This shortcut is useful when you can sort a mixed list of int and float and you want to have an absolute minimum and maximum for the link.

This shortcut was removed in Python 3000 (this is Python 3.2):

 >>> None < 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: NoneType() < int() 

In addition, Python3000 removed sys.maxint on the theory that all ints are pushed to long, and the limit is no longer applied.

PEP 326 , an example for upper and lower values, produced a min and max link in Python. New ordered behavior is documented .

Since PEP 326 was rejected, what are some useful, usable definitions for the min and max values ​​that work with integers and floats and longs in Python 2X and Python 3000?

Edit

Several answers go along the lines of "just use maxv = float (" inf ")" ... The reason why I think as much as possible is this:

 >>> float(2**5000) Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: long int too large to convert to float 

and

 >>> cmp(1.0**4999,10.0**5000) Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: (34, 'Result too large') 

However:

 >>> () > 2**5000 True 

In order for cmp to reach the value of float, float('inf') , the long value would need to be converted to float, and the conversion would raise OverflowError ...

Conclusion

Thank you all for your answers and comments. I chose the TryPyPy answer because it seemed the most embedded in what I asked: the absolute largest and absolute smallest value, as described on Wikipedia's entry for infinity.

With this question, I found out that the value of long or int is not converted to float to complete the comparison float('inf') > 2**5000 . I did not know that.

+21
python
May 14 '12 at 1:16
source share
3 answers

For numerical comparisons, +- float("inf") should work.

EDIT: It doesn't always work (but covers realistic cases):

 print(list(sorted([float("nan"), float("inf"), float("-inf"), float("nan"), float("nan")]))) # NaNs sort above and below +-Inf # However, sorting a container with NaNs makes little sense, so not a real issue. 

To have objects that are compared as above or below with any other arbitrary objects (including inf , but excluding other cheaters, as shown below), you can create classes that define their maximum / minimum values ​​in their special methods for comparison:

 class _max: def __lt__(self, other): return False def __gt__(self, other): return True class _min: def __lt__(self, other): return True def __gt__(self, other): return False MAX, MIN = _max(), _min() print(list(sorted([float("nan"), MAX, float('inf'), MIN, float('-inf'), 0,float("nan")]))) # [<__main__._min object at 0xb756298c>, nan, -inf, 0, inf, nan, <__main__._max object at 0xb756296c>] 

Of course, more effort is required to cover the β€œor equal” options. And this will not solve the general problem of the inability to sort the list containing None and int s, but this should also be possible with a little masking of the wrapping and / or decoration-sorting-undecorate (for example, sorting a list of tuples (typename, value) ).

+10
May 14 '12 at 3:52
source share

You have the most obvious choice in your question: float('-inf') and float('inf') .

Also, note that None smaller than everything, and an empty tuple that is higher than everything was never guaranteed in Py2, and, for example, Jython and PyPy have every right to use a different order if they like it, Everything, what is guaranteed is consistency within one running copy of the interpreter - the actual order is arbitrary.

+9
May 14 '12 at 1:26
source share

In cPython, cmp does not perform conversion to float implicitly. those. it works:

 >>> float('inf') > 2**5000 True 

Although this explicitly performs the conversion of fear:

 >>> float('inf') > float(2**5000) Overflow... 

The correct answer, IMHO, is not in itself a change in logic:

 def func_with_min(): minval=None for loop in list_with_mins: if minval is None or minval<minseen: # do that min thing you wanna do... 

If you want to make a difference, then float('-inf') for min and float('inf') pretty safe. However, remember to cache this outside the loop:

 def func(): minval=float('-inf') for loop in now_you_can_loop: # otherwise float('-inf') is kinda slow 
+3
May 14 '12 at 4:43
source share



All Articles