题目1:
有一个数组a,要求写一个方法,将这个数组拆分为两个子数组,要求两个子数组内的变量之和尽可能接近:
# -*- coding:utf-8 -*-import randomimport itertools#t_list = [1,5,6,7]length = input('请输入要产生的随机数个数:')#可以自己创建数组也可以随机生成t_list = []#保存原始数据t = int(length)for x in range(t):t_list.append(random.randint(1, 1000))#支持负数,如要测试负数,数据范围改一下即可medium = sum(t_list)/2#中值,作为判断依据print(t_list)#打印原始数组print(medium)#打印中值tuple_temp = ()abs_medium_tuple_sum_temp = 1000000 #该数据要大于随机值的mediumfor k in range(1,t,1): #遍历所有的组合情况,找到离medium最接近的组合for i in itertools.combinations(t_list,k):print(i)tuple_sum = sum(i)abs_medium_tuple_sum = abs(medium-tuple_sum)print("abs_medium_tuple_sum:"+str(abs_medium_tuple_sum))if abs_medium_tuple_sum_temp >= abs_medium_tuple_sum:abs_medium_tuple_sum_temp = abs_medium_tuple_sumprint("abs_medium_tuple_sum_temp:"+str(abs_medium_tuple_s