如何在 Python 中執行樓層劃分

已發表: 2022-11-02

在本教程中,您將學習如何在 Python 中執行地板除法。 您將使用 Python 的 // 運算符、Python 數學模塊中的 floor 函數等 - 以及代碼示例。

我們將從 Python 中算術運算符的概述開始,並了解下除法運算符 // 的工作原理。 然後,我們將學習如何使用其他等效方法,包括數學和運算符模塊中的函數來執行地板除法。

讓我們開始吧…

Python中的算術運算符

在 Python 中,您可以使用算術運算符對intfloat數據類型的數字執行簡單的算術運算。 這些運算符作用於操作數(數字)並返回運算結果。

Python中的算術運算符

下表總結了 Python 中的算術運算符及其工作原理:

操作員句法結果
加法 (+) num1+num2 返回num1num2之和
減法 (-) num1-num2 返回num1num2之間的差
乘法 (*) num1*num2 返回num1num2的乘積
求冪 (**) num1**num2 返回num1num2次方的結果; num1 num2
分配 (/) num1/num2 返回num1除以num2的結果——包括小數部分
樓層劃分 (/) num1//num2 返回num1除以num2時的商
模數 (%) num1 % num2 返回num1除以num2時的餘數

讓我們舉幾個使用這些算術運算符的例子。 您可以在 Python REPL 或 Geekflare 的在線 Python 編輯器中試用這些示例。

 >>> num1 = 18 >>> num2 = 5 >>> num1 + num2 23 >>> num1 - num2 13 >>> num1 * num2 90 >>> num1 ** num2 1889568

在本例中, num1為 18, num2為 5。除法運算num1/num2返回包含小數部分的結果。

數字 5 進入 18 三次,剩下的為 3。 因此,地板除法運算num1//num2給出商 3,而模運算符給出餘數——在這種情況下也是 3。

 >>> num1/num2 3.6 >>> num1//num2 3 >>> num1 % num2 3

這應該讓您了解除法、地板除法和模運算符的工作原理。 接下來,我們將詳細了解樓層除法算子。

️ 在 Python 2 中,除法運算 (/) 將結果截斷為最接近的整數——類似於 Python 3 中的底除法運算。本教程討論了 Python 3.x 中底除法運算的工作原理。

使用 // 運算符的樓層劃分

樓層劃分使用操作員

考慮一個帶有除數和除數的除法運算。 在num1/num2中, num1是被除數, num2是除數。 要執行num1num2的地板除法,請使用num1//num2

底除法運算符(//) 返回除法運算的商(整數或浮點數),具體取決於操作數的數據類型。

地板除法運算符不能確保答案始終是整數。 如果被除數 ( num1 ) 或除數 ( num2 ) 是浮點數,則num1//num2的結果是浮點數。 這裡有一些例子。

 >>> 18.0//5 3.0 >>> 10.0//4 2.0 >>> 15//4.0 3.0

如果您需要結果為整數,則需要使用int()函數將其顯式轉換為整數:

 >>> int(18.0//5) 3 >>> int(10.0//4) 2 >>> int(15//4.0) 3

引擎蓋下發生了什麼?

當您使用地板除法運算符 // 時,特殊方法(也稱為 dunder 方法) __floordiv__()被調用。 因此,您也可以對任何整數或浮點數使用__floordiv__()方法,如下所示:

 num1 = 18 num2 = 5 num1.__floordiv__(num2) # Output: 3

使用 operator.floordiv() 進行樓層劃分

Floor-Division-Using-operator.floordiv

要在 Python 中執行地板除法,您還可以使用operator模塊中的floordiv()函數

Python 的 operator 模塊包含可以執行所有算術運算的高效函數的定義。 因此,要執行地板除法,您還可以使用 operator 模塊中的floordiv()函數 - 而不是 // 運算符。

使用 operator 模塊中的floordiv()函數等效於使用地板除法運算符。

 >>> import operator >>> operator.floordiv(18,5) # Output: 3 >>> operator.floordiv(12,5.0) # Output: 2.0

使用 math.floor() 進行樓層劃分

地板功能如何工作?

在數學中, floor()函數將任何實數x作為輸入並返回一個整數(結果)。 該結果是小於或等於實數 x 的最大整數

為了更好地理解這一點,讓我們舉幾個例子,並在數軸上可視化這些數字。

示例 1 :考慮數字 2.3。 小於等於2.3的最大整數是2; 所以 floor(2.3) 將返回 2。

python-floordivision-教程-ex1

示例2:您也可以在處理負數時應用相同的定義。 考慮數字-1.7。 小於等於-1.7的最大整數是-2; 所以 floor(-1.7) 將返回 -2。

python-floordivision-tutorial-ex2

讓我們使用數學模塊中的floor()函數驗證上述結果。

 >>> from math import floor >>> floor(2.3) 2 >>> floor(-1.7) -2

要執行樓層劃分,您可以使用num1/num2作為參數調用floor()函數。 由於它將結果截斷或向下舍入到最接近的整數,它相當於地板除法運算。

您可以從math模塊顯式導入floor()函數,如下所示:

 from math import floor num1 = 18 num2 = 5 floor(num1/num2) # Output: 3

或者,您也可以只導入math模塊,然後使用math.floor()訪問floor()函數。

 import math num1 = 18 num2 = 5 math.floor(num1/num2) # Output: 3

與 operator 模塊中的floordiv()函數和地板除法運算符 // 不同,使用math.floor(num1/num2)可確保結果為整數。 這種方法使代碼可讀並消除了類型轉換步驟。

 import math num1 = 18.0 num2 = 5 math.floor(num1/num2) # Output: 3

Python中的樓層劃分示例

Python 中的樓層劃分示例

讓我們用一個實際的例子來結束我們的討論:二分搜索。

二進制搜索是一種高效的搜索算法,可讓您在O(log n)時間內通過排序數組搜索目標元素,其中n是數組的大小。

該算法通過在每一步將搜索間隔分成兩半來工作。 這取決於間隔的中點是否與目標匹配(搜索在找到匹配時結束!)或小於或大於目標。 由於數組的大小在每一步都減少了一半,因此中點並不總是計算為整數。

 itemlist = [5,7,18,21,34,45] item = 7

考慮以下二分搜索算法的實現。 函數binary_search()接受一個數字 ( item ) 和一個列表 ( itemlist ) 並在itemlist中搜索該item的出現。

  • 如果找到該item ,則該函數返回該item出現的索引。
  • 否則,它返回None
 def binary_search(item, itemlist): # get the list size listsize = len(itemlist) - 1 # start at the two ends of the list lowerIdx = 0 upperIdx = listsize while lowerIdx <= upperIdx: # calculate the middle point # use normal division instead of floor division midPt = (lowerIdx + upperIdx)/ 2 # if item is found, return the index if itemlist[midPt] == item: return midPt # otherwise get the next midpoint if item > itemlist[midPt]: lowerIdx = midPt + 1 else: upperIdx = midPt - 1 if lowerIdx > upperIdx: return None

這個實現在功能上是正確的,除了我們沒有考慮到在搜索進行時midPt不評估為整數。

 binary_search(item,itemlist)

如果我們調用該函數,我們會遇到一個TypeError ,指出列表索引必須是整數或切片,而不是浮點數。

 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-a5f12ebc3145> in <module> ----> 1 binary_search(item,itemlist) <ipython-input-2-524ef6900b1f> in binary_search(item, itemlist) 12 13 # if item is found, return the index ---> 14 if itemlist[midPt] == item: 15 return midPt 16 # otherwise get the next midpoint TypeError: list indices must be integers or slices, not float

我們修改函數定義以使用地板除法運算符:

 def binary_search(item, itemlist): # get the list size listsize = len(itemlist) - 1 # start at the two ends of the list lowerIdx = 0 upperIdx = listsize while lowerIdx <= upperIdx: # calculate the middle point # use floor division midPt = (lowerIdx + upperIdx)// 2 # if item is found, return the index if itemlist[midPt] == item: return midPt # otherwise get the next midpoint if item > itemlist[midPt]: lowerIdx = midPt + 1 else: upperIdx = midPt - 1 if lowerIdx > upperIdx: return None

該函數返回找到項目 7 的索引,即索引 1。

 binary_search(item,itemlist) # Output: 1

結論

我希望本教程能幫助您了解如何在 Python 中執行地板除法。 以下是您學到的不同方法的摘要:

  • 在 Python 中, a 運算符 b以 a 和 b 為操作數執行運算符定義的運算,並返回運算結果。
  • 您可以使用 Python 的地板除法運算符 //; a//b返回除法運算 a/b 的商。
  • 或者,您可以使用 Python 的 operator 模塊中定義的等效floordiv()函數,語法為: operator.floordiv(a,b)來獲取 a//b 的結果。
  • 以上所有方法都返回商,但數據類型可以是浮點數或整數,具體取決於 a 和 b 的值。 因此,您必須將返回值轉換為整數。
  • Python 數學模塊中的floor()函數也可用於執行地板除法: math.floor(a,b)等價於a//b並返回一個整數。 如果您希望結果為整數,請考慮使用數學模塊中的 floor 函數。

接下來,學習如何在 Python 中使用 defaultdict。