基本思路:
让数组a的每一个对数组b尝试能不能交换,
所谓能交换,就是交换过后,两数组和之差比当前小。我设想了一个迭代算法,就是将当前的交换尝试,重复,直到没有一个值再能交换为止!
代码如下:
1 a = [170, 100, 5, 4, 3, 2, 1] 2 b = [101, 100, 15, 14, 13, 12, 11] 3 lena = len(a) 4 lenb = len(b) 5 print sum(a) 6 print sum(b) 7 d = abs(sum(a) - sum(b)) 8 9 10 def exchange(i, j): 11 temp = a[i] 12 a[i] = b[j] 13 b[j] = temp 14 15 n = 0 16 17 while(True): 18 n += 1 19 flag = False 20 for i in range(0, lena): 21 for j in range(0, lenb): 22 exchange(i, j) 23 dtemp = abs(sum(a) - sum(b)) 24 if dtemp < d: 25 d = dtemp 26 flag = True 27 else: 28 exchange(i, j) 29 print a, '\n', sum(a), '\n', b, '\n', sum(b) 30 if flag == False: 31 break 32 print n 33