本帖最后由 阴阳神万物主 于 2019-10-31 10:35 编辑
就目前而言,我读题理解出的意思为:求给定全集的两个交集为空的子集,使得两个集合间元素总和的差值最大
不晓得对不对,如果不对,我再改def solve(put:list,who:bool =False)->int:
temp = list(set(put))
temp.sort()
B = [x for x in temp if x<=0 ]
if len(B) == len(temp):
if who:
print('A =',list(temp[-1]),'B = ',B[:-1])
return temp[-1] - sum(B[:-1])
elif not len(B):
if who:
print('A =',temp[1:],'B = ',[temp[0]])
return sum(temp[1:]) - temp[0]
else:
if who:
print('A =',temp[len(B):],'B = ',B)
return sum(temp[len(B):]) - sum(B)
if __name__ == '__main__':
print('示例1 输出:',solve([1,2,-3,1]))
print('示例2 输出:',solve([0,-1]))
简化一下代码,美化一下:def solve(put:list,who:bool =False)->int:
temp = list(set(put))
temp.sort()
B = [x for x in temp if x<=0 ]
if len(B) == len(temp):
A,B = [temp[-1]], B[:-1]
elif not len(B):
A,B = temp[1:] , [temp[0]]
else:
A,B = temp[len(B):] , B
if who:
print('A =',A,'B = ',B)
return sum(A) - sum(B)
if __name__ == '__main__':
print('示例1 输出:',solve([1,2,-3,1]))
print('示例2 输出:',solve([0,-1]))
|