交换两个列表使两个列表元素和的差最小,写的思路就是双重循环,外层列表中的元素依次与内层列表计算diff差值,小于最小差值则交换元素,如果diff<>0则递归执行该方法,否则diff==0则退出,打印出最后列表。现在的问题是双重循环无法退出,当diff==0时还继续执行了
代码如下:
class GetOutOfLoop( Exception ):
pass
def mean(a, b):
try:
rMin=sum(a)-sum(b)
for i in range(len(a)):
for j in range(len(b)):
diff=(sum(a)-a[i]+b[j])-(sum(b)-b[j]+a[i])
if diff<0:
diff=-diff
if diff<rMin:
b.append(a[i])
a.append(b[j])
b.remove(b[j])
a.remove(a[i])
print 'diff=%d,rMin=%d'%(diff,rMin)
print a,sum(a)
print b,sum(b)
rMin=diff
if rMin==0:
raise GetOutOfLoop
mean(a,b)
except GetOutOfLoop:
pass
def main():
a = [7, 9, 10]
b = [6, 2, 8]
mean(a, b)
print 'result:'
print sum(a)-sum(b)
print (a)
print (b)
if __name__ == '__main__':
main()
现在运行结果:
D:\Python27>python D:\pythoncode\min_sum.py
diff=8,rMin=10
[9, 10, 6] 25
[2, 8, 7] 17
diff=6,rMin=8
[10, 6, 2] 18
[8, 7, 9] 24
diff=2,rMin=6
[10, 2, 8] 20
[7, 9, 6] 22
diff=0,rMin=2
[10, 2, 9] 21
[7, 6, 8] 21
diff=4,rMin=6
[2, 9, 8] 19
[7, 6, 10] 23
diff=2,rMin=4
[2, 8, 10] 20
[7, 6, 9] 22
def mean(a, b): rMin=sum(a)-sum(b) mark=0 for i in range(len(a)): for j in range(len(b)): diff= rMin+b[j]*2-a[i]*2 #这个地方可以写的简单一点 if abs(diff)<abs(rMin): b.append(a[i]) a.append(b[j]) b.remove(b[j]) a.remove(a[i]) print 'diff=%d,rMin=%d'%(diff,rMin) print a,sum(a) print b,sum(b) rMin=diff mean(a,b) #only modified to call this if rMin==0: mark=1 break #mean(a,b) ,不能在这里递归调用,这样的话,i和j的值始终都是0 if mark == 1: break def main(): a = [7, 9, 10] b = [6, 2, 8] mean(a, b) print 'result:' print sum(a)-sum(b) print (a) print (b) if __name__ == '__main__': main()
@Double_win,你写的这个方法还是不行哦
元素和的差最小:第一步先排序,以及两列表list1,list2分别求和,最后diff=(list1-list2),如果diff大于0,取diff(n)=list1的最大值减list2的最小值,diff=diff-diff(n),判断diff值是否减小,减小则交换 依次循环