设A是一组非空整数.编写一个函数find,输出具有最大乘积的A的非空子集.例如,find([ - 1,-2,-3,0,2])= 12 =( - 2)*( - 3)*2
这就是我的想法:将列表分成正整数列表和负整数列表:
这是我在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)
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?PS这是来自Google的foobar挑战的一个问题,我显然错过了一个案例,但我不知道哪个.
这是另一个不需要库的解决方案:
def find(l):
if len(l) <= 2 and 0 in l: # This is the missing case, try [-3,0], it should return 0
return max(l)
l = [e for e in l if e != 0] # remove 0s
r = 1
for e in l: # multiply all
r *= e
if r < 0: # if the result is negative, remove biggest negative number and retry
l.remove(max([e for e in l if e < 0]))
r = find(l)
return r
print(find([-1, -2, -3, 0, 2])) # 12
print(find([-3, 0])) # 0
Run Code Online (Sandbox Code Playgroud)
编辑 :
我想我已经找到了缺失的情况,即列表中只有两个元素,并且最高的是 0。