qingcheng奕  
counts = [98,12,3,4,1,4,9,3821]
minNum = min(counts)
#print minNum
minNum_index = counts.index(minNum)
#print minNum_index

#找出列表中最小的2个元素
def find_two_smallest(L):
    smallest = min(L)
    min_index = L.index(smallest)
    L.remove(smallest)
    
    smallest2 = min(L)
    min_index2 = L.index(smallest2)
    L.remove(smallest2)
 
    L.insert(min_index,smallest)
    L.insert(min_index2,smallest2)
    
    if min_index <= min_index2:
        min_index2 +=1

    return (smallest,smallest2)


ansList = find_two_smallest(counts)
print ansList

#第二种方式
def find_two_smallest2(L):
    tempList = L[:]
    tempList.sort()
    return (tempList[0],tempList[1])

ansList2 = find_two_smallest2(counts)
print ansList2


#搜索
def linear_search(v,L):
    i = 0
    while i<len(L) and L[i] != v:
        i = i+1
    return i

print linear_search(7,counts)
print linear_search(12,counts)

#计算花费的时间
import time
def linear_search2(v,L):
    i = 0
    for value in L:
        if value == v:
            return i
        i = i+1
    return len(L)


L = range(1000001)
time1 = time.time()
linear_search(7,L)
linear_search(500000,L)
time2 = time.time()
print (time2-time1)*1000

L = range(10)
print L


#二分搜索
def binary_search(v,L):
    i = 0
    j = len(L) -1
    while i <= j:
        m = (i+j)/2
        if(L[m]<v):
            i = m +1
        else:
            j = m - 1
    if 0 <= i <len(L) and L[i] == v:
        return i
    else:
        return -1

#测试
VALUES = [1,3,4,6,8,9,10]
assert binary_search(1,VALUES) == 0
assert binary_search(2,VALUES) == -1

 

posted on 2014-03-05 20:41  qingcheng奕  阅读(221)  评论(0编辑  收藏  举报