# python无法退出双重循环问题

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

0
```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 | 园豆：244 (菜鸟二级) | 2014-04-24 17:13

@Double_win，你写的这个方法还是不行哦

0

leemiracle | 园豆：202 (菜鸟二级) | 2015-12-29 12:36

您需要登录以后才能回答，未注册用户请先注册