像这样:
def foo(lst): total_sum = sum(lst) i = 1 while sum(lst[:i]) < total_sum / 2: # iterate over the list slices until we hit the "middle" if sum(lst[:i+1]) >= total_sum / 2: # also make sure that we won't go further break i += 1 return [lst[:i], lst[i:]]
测试:
[[10], [1, 1, 1]] # 10 + 3[[2, 5], [9, 5, 1, 1]] # 7 + 16[[9, 5, 5, 8, 2, 2], [18, 8, 3, 9, 4]] # 31 + 42[[17, 15, 2, 18, 7], [20, 3, 20, 12, 7]] # 59 + 62[[19, 8, 9, 1], [14, 1, 16, 4, 15, 5]] # 37 + 55
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)