Reputation: 7411
I am trying to implement a Heap defined Priority Queue, the algorithm is from CLRS book chapter 6. The pseudocode is listed below:
Max_Heap_Insert(A, key):
A.heap_size = A.heap_size + 1
A[A.heap_size] = -∞
Heap_Increase_Key(A, A.heap_size, key)
My question is that using python, how do I define -∞?
Upvotes: 35
Views: 38539
Reputation: 486
I stumbled across this while working on a heap implementation myself. :)
As of Python 3.5, you can use the inf constant from the math module
from math import inf
inf + inf # inf
inf - inf # nan
inf / inf # nan
inf * inf # inf
max(list(range(1_000_000)) + [inf]) # inf
min(list(range(-1_000_000, 1)) + [-inf]) # -inf
I did not know this and used a custom class to achieve the same ordering property
class MinusInf:
def __gt__(self, other):
return False
def __ge__(self):
return False
def __lt__(self, other):
return True
def __le__(self, other):
return True
def __eq__(self, other):
return False
minus_inf = MinusInf()
minus_inf >= -1_000_000 # False
This will work for the purpose of a heap, but the recommended way is to just use math.inf
(or numpy.inf
which is the inf constant from numpy).
Upvotes: 4
Reputation: 413
As it happens, in Python 2, None
is less than any integer, so you can use None
. In Python 3 you have (at least) four choices:
None
, and whenever you compare two values, explicitly test for them being None
.Heap-Increase-Key
somehow.Upvotes: 6