There are two sequences, a, B, the size is n, the value of the sequence element arbitrarily shaped number, unordered;
Requirement: To minimize the difference between the and of [sequence A and] and [sequence B elements] by exchanging the elements in A/b.
1. Combine the two sequences into a sequence and sort them to get sourcelist
2. Take out the largest element big, the second largest element small
3. Divide the remaining sequence s[:-2] to get the sequence Max,min
4. Add the small to the max sequence, add big to the min sequence, recalculate the new sequence, and large for max, small for Min.
As follows, provides a recursive version and iterative version of the idea of disintegration:
#!/usr/bin/env python#-*-coding:utf-8-*-####################################################################### # # # File name:mindistance.py# author:lpqiu# mail: [email protected]# Created time:2014 year October 27 Monday 05:19 45 seconds ####### ################################################################### recusive versiondef minDist (sortedList): If not Sortedlist:return ([], []) large = sortedlist[-1] Secondlarge = sortedlist[-2] largelist, smalllist = min Dist (Sortedlist[:-2]) largelist.append (secondlarge) smalllist.append (Large) #print (' largelist: ', Largelist, ' Smal Llist ', smalllist) if sum (largelist) > sum (smalllist): Return (Largelist, smalllist) Else:return ( Smalllist, largelist) # iteriation versiondef mindistiterver (sortedList): largelist, smalllist = [], [] for i in rang E (0, Len (sortedList), 2): If SUM (largelist) > sum (smalllist): Largelist.append (Sortedlist[i]) Smalllist.append (sortedlist[i+ 1]) else:largeList.append (sortedlist[i + 1]) Smalllist.append (sortedlist[i]) if sum (lar gelist) > Sum (smalllist): Return (Largelist, smalllist) Else:return (Smalllist, largelist) def Testmai N (ListA, Listb): # len (listA) = = Len (listb) = n Print ("Sorted List:", Sorted (ListA + listb)) LA Rgelist, smalllist = mindist (sorted (ListA + Listb)) print (Largelist, smalllist, "Distance:", sum (largelist)-SUM (smal llist)) Largelistiterver, smalllistiterver = Mindistiterver (sorted (ListA + Listb)) print (Largelistiterver, smalllist Iterver, "Distance:", sum (largelistiterver)-sum (smalllistiterver)) if __name__ = = "__main__": ListA = [1,-1,2,3,6,189 ]; LISTB = [2,3,4,6,7,123] Testmain (ListA, Listb)