Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3818
  • 博文数量: 2
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 32
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-08 15:07
文章分类

全部博文(2)

文章存档

2014年(2)

我的朋友
最近访客

分类: Python/Ruby

2014-05-08 16:02:45

有两个序列a,b,大小都为n,序列元素的值任意整形数,无序;
要求:通过交换a,b中的元素,使[序列a元素的和]与[序列b元素的和]之间的差最小。
只能想到最傻的办法
import random
import time
def timeit(func):
    def _deco(*args, **kwargs):
        start = time.clock()
        d = func(*args, **kwargs)
        end = time.clock()
        print "used time: %s" % str(end - start)
        return d
    return _deco

@timeit
def exchange(lsta, lstb):
    suma = sum(lsta)
    sumb = sum(lstb)
    d = abs(suma-sumb)
    if d == 0:
        return d
    
    bExchange = False    
    for indexa, ia in enumerate(lsta):
        if d == 0:
            break
        for indexb, ib in enumerate(lstb):
            tempd = abs((suma-ia+ib)-(sumb+ia-ib))
            if tempd < d:
                bExchange = True
                tempindexa = indexa
                tempindexb = indexb
                d = tempd

        if bExchange:
            suma = suma - lsta[tempindexa] + lstb[tempindexb]
            sumb = sumb - lstb[tempindexb] + lsta[tempindexa]
            tempv = lsta[tempindexa]
            lsta[tempindexa] = lstb[tempindexb]
            lstb[tempindexb] = tempv
            bExchange = False
        
    return d
lsta = []
lstb = []
for i in range(1000):
    lsta.append(random.randint(0, 1000000))
for i in range(1000):
    lstb.append(random.randint(0, 1000000))

print exchange(lsta,lstb)

lsta = []
lstb = []
for i in range(10000):
    lsta.append(random.randint(0, 1000000))
for i in range(10000):
    lstb.append(random.randint(0, 1000000))

print exchange(lsta,lstb)
=======================================================
分别测试一千个数和一万个数的结果,一万个数时耗时真多。
>>> 
used time: 0.223763605341
3
used time: 46.6022585932
1
>>> 

阅读(927) | 评论(1) | 转发(0) |
0

上一篇:没有了

下一篇:python学习,计算文件MD5值

给主人留下些什么吧!~~

7大爷2014-05-09 09:42:05

不错啊