[英]How to implement negative infinity in python?
我正在嘗試實現堆定義的優先級隊列,該算法來自 CLRS 書籍第 6 章。偽代碼如下所列:
Max_Heap_Insert(A, key):
A.heap_size = A.heap_size + 1
A[A.heap_size] = -∞
Heap_Increase_Key(A, A.heap_size, key)
我的問題是,使用 python,如何定義 -∞?
Python有特殊值float('inf')
和float('-inf')
。
碰巧,在Python 2中, None
小於任何整數,因此您可以使用None
。 在Python 3中,您有(至少)四種選擇:
None
,每當比較兩個值時,顯式測試它們為None
。 Heap-Increase-Key
。 我自己在處理堆實現時偶然發現了這一點。 :)
從 Python 3.5 開始,您可以使用數學模塊中的 inf 常量
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
我不知道這一點並使用自定義 class 來實現相同的排序屬性
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
這將用於堆的目的,但推薦的方法是只使用math.inf
(或numpy.inf
,它是 numpy 的 inf 常量)。
使用數學庫,您可以:
import math
a = -math.inf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.