2021-02-04 [day35] Python百日打卡学习自【夸可编程】

'''
题目

给定一个数组a,返回位置i,使得sum(a[: i + 1])和sum(a[i + 1 : ])最接近
如果有多个满足条件的位置,返回最小的那个
例子

nearest_split_sum([7,3,2,8,0,-1,9]) -> 2
nearest_split_sum([1,1,0,1,1]) -> 1
nearest_split_sum([1]) -> 0
假设

输入的数组不为空
tips

利用之前的分段和计算新的分段和
代码:
'''

def nearest_split_sum(a):
    res = []
    mins = []
    for i in range(len(a)):
        if i == 0:
            res.append((a[0], sum(a) - a[0]))
        else:
            res.append((res[-1][0] + a[i], res[-1][1] - a[i]))
        mins.append(abs(res[-1][0] - res[-1][1]))
    print(res)
    print(mins)
    print(min(mins))
    return mins.index(min(mins))


# print(nearest_split_sum([7,3,2,8,0,-1,9]))# -> 2
print(nearest_split_sum([1,1,0,1,1]))# -> 1
# print(nearest_split_sum([1]))# -> 0
# print(nearest_split_sum([1,2,3]))# -> 1

你可能感兴趣的:(2021-02-04 [day35] Python百日打卡学习自【夸可编程】)