我需要从一系列数字中找到最大的产品。SO-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)我在想一件事
。
我在这里错过了什么?
发布于 2022-10-04 14:41:00
下面是一些失败的测试用例:
[-5, 8]
[-5, 0]
[-1, 0, 2]
[0]一些问题:
len(negatives) > 1不正确。如果是len(negatives) == 1,那么您肯定不希望在产品中使用该负值,除非是数组中的唯一值.时,正积的默认值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_producthttps://stackoverflow.com/questions/73948081
复制相似问题