Python 求一个列表的最小值

2018-06-17  本文已影响0人  Golden_humble
def findMin(alist):
    start = time.time()
    findMin = alist[0];
    for i in range(1,len(alist)):
        if alist[i] < findMin:
            findMin = alist[i]
    end = time.time()
    return findMin,end-start

结果如下:

for i in range(5):
    print("the minimum is %d, the process required %10.7f seconds"%(findMin(list(random.randint(1,100) for i in range(1000000)))))
    
the minimum is 1, the process required  0.1043806 seconds
the minimum is 1, the process required  0.0833511 seconds
the minimum is 1, the process required  0.1031568 seconds
the minimum is 1, the process required  0.1031709 seconds
the minimum is 1, the process required  0.0906184 seconds

函数改进一下:

def findMin(alist):
    start = time.time()
    findMin = alist[0];
    for i in alist:
        if i < findMin:
            findMin = i
    end = time.time()
    return findMin,end-start

因为python 中for循环可以对元素进行遍历,所以可以这样写。
结果如下:

for i in range(5):
    print("the minimum is %d, the process required %10.7f seconds"%(findMin_1(list(random.randint(1,100) for i in range(1000000)))))
    
the minimum is 1, the process required  0.0530787 seconds
the minimum is 1, the process required  0.0150602 seconds
the minimum is 1, the process required  0.0606675 seconds
the minimum is 1, the process required  0.0580323 seconds
the minimum is 1, the process required  0.0625741 seconds

运行时间比上一种方法要短。

上一篇 下一篇

猜你喜欢

热点阅读