首页 > 编程语言 > 详细

Python学习笔记2_一些小程序

时间:2014-03-06 03:25:25      阅读:456      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
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
bubuko.com,布布扣

Python学习笔记2_一些小程序,布布扣,bubuko.com

Python学习笔记2_一些小程序

原文:http://www.cnblogs.com/qingcheng/p/3583305.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!