python - 找到具有最大乘积的一组整数的子集

标签 python algorithm

令 A 为非空整数集。编写一个函数 find 输出 A 的非空子集,该子集具有最大乘积。例如,find([-1, -2, -3, 0, 2]) = 12 = (-2)*(-3)*2

这是我的想法:将列表分为正整数列表和负整数列表:

  1. 如果我们有偶数个负整数,将两个列表中的所有内容相乘,我们就有了答案。
  2. 如果我们有奇数个负整数,找出最大的一个并将其从列表中移除。然后将两个列表中的所有内容相乘。
  3. 如果列表只有一个元素,则返回该元素。

这是我的 Python 代码:

def find(xs):
    neg_int = []
    pos_int = []
    if len(xs) == 1:
        return str(xs[0])
    for i in xs:
        if i < 0:
            neg_int.append(i)
        elif i > 0:
            pos_int.append(i)
    if len(neg_int) == 1 and len(pos_int) == 0 and 0 in xs:
        return str(0)
    if len(neg_int) == len(pos_int) == 0:
        return str(0)
    max = 1
    if len(pos_int) > 0:
        for x in pos_int:
            max=x*max
    if len(neg_int) % 2 == 1:
        max_neg = neg_int[0]
        for j in neg_int:
            if j > max_neg:
                max_neg = j
        neg_int.remove(max_neg)
    for k in neg_int:
        max = k*max
    return str(max)

我错过了什么吗?附言这是来自 Google 的 foobar 挑战的问题,我显然遗漏了一个案例,但我不知道是哪个案例。

现在这是实际问题: enter image description here

最佳答案

from functools import reduce
from operator import mul

def find(array):
    negative = []
    positive = []
    zero = None
    removed = None

    def string_product(iterable):
        return str(reduce(mul, iterable, 1))

    for number in array:
        if number < 0:
            negative.append(number)
        elif number > 0:
            positive.append(number)
        else:
            zero = str(number)

    if negative:
        if len(negative) % 2 == 0:
            return string_product(negative + positive)

        removed = max(negative)

        negative.remove(removed)

        if negative:
            return string_product(negative + positive)

    if positive:
        return string_product(positive)

    return zero or str(removed)

关于python - 找到具有最大乘积的一组整数的子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39844473/

相关文章:

c# - 如何修改 dijkstra 算法以找到所有可能的路径?

algorithm - 在 DAG 中寻找给定长度 N 的路径

c# - 检测地理位置是否在复杂的多边形中

python - 为什么 subprocess.Popen 返回码与 bash 的类似命令不同

python - tf.squeeze 和 tf.nn.rnn 函数有什么作用?

python - Pyspark StructType 未定义

algorithm - 什么是模拟和比较旅程的简单系统?

python - 如何使用函数从数据框列中获取第一个和最后一个值

python - Pandas 数据帧 : Grouping columns having the same first characters

algorithm - 如何解决 MaxCounters - Coditility with Golang