在什么样的测试用例中,这可能无法给出正确的输出,还有哪些潜在的解决方案?

2024-09-30 12:16:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要得到一个整数列表,并将它的元素相乘,这样我就得到了可能的最大数。这个数字,我需要输出为字符串。 示例:

(int list) givenList = [2, 0, 2, 2, 0]
Output: 8  
//because (2)*(2)*(2)=8

(int list) givenList= [-2, -3, 4, -5]
Output:60  
//because (-3)*(-5)*(4)=60

这是我的密码:

import operator
xs = [0,0]
if  xs.count(0) == len(xs) :
    print ("0")
elif xs.count(0) == len(xs)-1:
    print ("0")
else:
    negatives =[]
    legits = []
    listLength=len(xs)
    counter = 0
    while counter < listLength:
        if xs[counter] <0:
            negatives.append(xs[counter])
        if xs[counter] > 0:
            legits.append(xs[counter])
        counter = counter +1

    if len(negatives)%2 !=0:
        negatives[negatives.index(max([n for n in negatives if n<0]))] = 1

    newList = negatives + legits
    print str((reduce(operator.mul, newList)))

Tags: outputlenifcountcounteroperatorlistint

热门问题