Google Foobar测试用例失败

时间:2016-11-12 01:00:42

标签: python arrays

我正在完成谷歌foobar挑战,但对于我的生活,我无法通过第四个测试案例,这是挑战:

您需要确定任何给定阵列中哪些面板可以离线修复,同时仍然保持每个阵列的最大功率输出量,并且要做到这一点,您首先需要弄清楚最大值实际上每个数组的输出。编写一个函数答案(xs),它取一个表示数组中每个面板的功率输出电平的整数列表,并返回这些数字的某些非空子集的最大乘积。因此,例如,如果一个数组包含功率输出电平为[2,-3,1,0,-5]的面板,则可以通过获取子集来找到最大乘积:

xs[0] = 2, xs[1] = -3, xs[4] = -5, giving the product 2*(-3)*(-5) = 30. So answer([2,-3,1,0,-5]) will be "30".

每个太阳能电池板阵列包含至少1个且不超过50个电池板,每个电池板的功率输出电平绝对值不大于1000(某些电池板故障严重,导致能量消耗,但你知道面板的波形稳定器可以让你结合两个负输出面板来产生多个功率值的正输出。最终产品可能非常大,因此请将答案作为数字的字符串表示。

以下是一些给定的测试用例:

测试用例

Inputs:
    (int list) xs = [2, 0, 2, 2, 0]
Output:
    (string) "8"

Inputs:
    (int list) xs = [-2, -3, 4, -5]
Output:
    (string) "60"

这是我的代码:

def product_of_values(lst):
    product = 1
    if len(lst) > 0:
        for x in lst:
            product *= x
    return product




def answer(xs):
    # two seperate list for positive and negative values
    positive_list = [x for x in xs if x > 0]
    negative_list = [x for x in xs if x < 0]
    pos_product = product_of_values(pos_list)

# multiplication of an even number of negatives == positive value
if len(negative_list) % 2 == 0:
    negative_product = product_of_values(negative_list)

# if length of negative_list is odd, pop value closest to zero
else:
    neg_list.remove(max(neg_list))
    neg_product = product_of_values(neg_list)

# If there is only one negative value in the negative_list, return 0.
if len(pos_list) < 1 and len(neg_list) <= 1:
    return '0'
else:
    return str(neg_product * pos_product)
我错过了一些明显的东西吗?

2 个答案:

答案 0 :(得分:1)

@edi_allen我也面临着同样的问题。我已经用Java编写了代码,可见的测试用例正在我的编译器中传递,但是在foobar上失败。您是如何克服这一难题的?下面是我的代码:

public static String solution(int[] xs) {

        if(xs.length < 1 || xs.length > 50) {
            return "0";
        }

        Arrays.parallelSort(xs);

        for(int i = 1; i < xs.length ; i++) {
            if(xs[i] < 0 && xs[i-1] < 0) {
                xs[i-1] = Math.abs(xs[i-1]);
                xs[i] = Math.abs(xs[i]);
            }
        }

        BigInteger prod = null;
        for(int i = 0; i < xs.length ; i++) {
            if(Math.abs(xs[i]) > 1000) {
                return "0";
            }
            else if(xs[i] <= 0) {
                continue;
            }
            else if(prod == null){
                prod = new BigInteger(String.valueOf(xs[i]));
            }
            else {
                prod = prod.multiply(new BigInteger(String.valueOf(xs[i])));
            }
        }
        if(prod == null) {
            return "0";
        }

        return prod.toString();
    }

答案 1 :(得分:0)

这可能是时间问题的复杂性。

对于产品试试这个 -

from operator import mul
reduce(mul, list, 1)
相关问题