首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在数组中查找数字的乘积

在数组中查找数字的乘积
EN

Stack Overflow用户
提问于 2022-10-04 12:47:11
回答 1查看 91关注 0票数 1

我需要从一系列数字中找到最大的产品。SO-2,-3,4,-5将返回60,因为(-5)(4)(-3)=60。

到目前为止,我已经提出了下面的代码,它通过了上面的测试用例,但是对于一些隐藏的边缘情况却失败了。

代码语言:javascript
复制
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)

我在想一件事

  1. 得到所有正整数的乘积。(因为它们总是产生最大的结果)
  2. 过滤器并对负整数进行排序。如果负整数的数目是偶数,则乘以它们得到最终乘积。如果负整数的数目是奇数,则删除最小/最后的整数并执行步骤3.

我在这里错过了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-04 14:41:00

下面是一些失败的测试用例:

代码语言:javascript
复制
[-5, 8]
[-5, 0]
[-1, 0, 2]
[0]

一些问题:

  • 条件len(negatives) > 1不正确。如果是len(negatives) == 1,那么您肯定不希望在产品中使用该负值,除非是数组中的唯一值.

  • 当唯一的非负值为0.

时,正积的默认值1是错误的。

  • 不知道为什么要将产品转换成字符串.

以下是一项更正:

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73948081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档