簡體   English   中英

如何在python中實現負無窮大?

[英]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中,您有(至少)四種選擇:

  1. 使用min(A) - 1。
  2. 使用None ,每當比較兩個值時,顯式測試它們為None
  3. 定義一個由整數或-∞組成的新數據類型,並正確處理比較。
  4. 修改算法以消除第2行。 你必須以某種方式修補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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM