Python 中的連續元素最大乘積


Python 擁有出色的庫來處理資料。我們可能會需要查詢構成大字串一部分的兩個連續數字的最大乘積。本文介紹實現這一目標的方法。

使用 zip 和 max

將字串轉換為列表。然後使用切片從連續元素建立成對。應用 * 乘以對,然後從每對的乘積結果中獲取最大值。

示例

 線上演示

Astring = '5238521'
# Given string
print("Given String : ",Astring)
# Convert to list
Astring = list(Astring)
print("String converted to list:\n",Astring)
# Using max()
res = max(int(a) * int(b) for a, b in zip(Astring, Astring[1:]))
# Result
print("The maximum consecutive product is : " ,res)

輸出

執行上述程式碼為我們提供了以下結果 -

Given String : 5238521
String converted to list:
['5', '2', '3', '8', '5', '2', '1']
The maximum consecutive product is : 40

使用 map 和 max

我們採取與上面類似的方法。但我們使用 map 函式繼續生成連續整數對。然後使用 operator 模組中的 mul 函式來乘以此對中的數字。最後應用 max 函式以獲得結果的最大值。

示例

from operator import mul
Astring = '5238521'
# Given string
print("Given String : ",Astring)
# Convert to list
Astring = list(Astring)
print("String converted to list:\n",Astring)
# Using max()
res = max(map(mul, map(int, Astring), map(int, Astring[1:])))
# Result
print("The maximum consecutive product is : " ,res)

輸出

執行上述程式碼為我們提供了以下結果 -

Given String : 5238521
String converted to list:
['5', '2', '3', '8', '5', '2', '1']
The maximum consecutive product is : 40

更新日期: 20-May-2020

262 次瀏覽

職業

完成課程,獲得認證

開始
廣告