我需要從一組數字中找到最大的產品。所以 [-2, -3, 4, -5] 將回傳 60,因為 (-5)(4)(-3)=60
到目前為止,我已經提出了以下代碼,這通過了上述測驗用例,但對于一些隱藏的邊緣情況則失敗了。
def largest_product(arr):
negatives = sorted([n for n in arr if n < 0])
positive_product = negative_product = 1
if len(negatives) % 2 != 0 and len(arr) > 1 and len(negatives) > 1:
negatives.pop()
for n in arr:
positive_product *= n if n > 0 else 1
for n in negatives:
negative_product *= n
return str(positive_product * negative_product)
我在想一些事情
- 獲取所有正整數的乘積。(因為他們總是產生最好的結果)
- 過濾和排序負整數。
- 如果負整數的個數是偶數,則將它們相乘得到最終乘積。
- 如果負整數的個數是奇數,則洗掉最小/最后一個整數并執行第 3 步。
我在這里想念什么?
uj5u.com熱心網友回復:
以下是一些失敗的測驗用例:
[-5, 8]
[-5, 0]
[-1, 0, 2]
[0]
一些問題:
條件
len(negatives) > 1不正確。如果len(negatives) == 1那么您肯定不想在產品中使用該負值,除非它是陣列中的唯一值。當唯一的非負值是 0 時,正積的默認值 1 是錯誤的。
不知道為什么將產品轉換為字串...
這是一個更正:
def largest_product(arr):
if not arr: # No choice => no product
return
if len(arr) == 1: # One choice => take it
return arr[0]
negatives = sorted([n for n in arr if n < 0])
positive_product = negative_product = 1
if len(negatives) % 2 != 0: # corrected condition
negatives.pop()
if max(arr) == 0 and not negatives: # special case
return 0
for n in arr:
positive_product *= n if n > 0 else 1
for n in negatives:
negative_product *= n
return positive_product * negative_product
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/512352.html
上一篇:如何使用for回圈回傳串列中“movie”=[“spiderman”、“endgame”、“justiceleague”、“batman”]的值
