zoukankan      html  css  js  c++  java
  • Python学习笔记2_一些小程序

    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
  • 相关阅读:
    完美世界笔试(动态规划,背包问题)
    腾讯笔试3
    腾讯笔试2
    腾讯笔试1
    阿里笔试1
    Merge Sorted Array
    Partition List
    Reverse Linked List II
    Remove Duplicates from Sorted List II
    白菜刷LeetCode记-704. Binary Search
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3583305.html
Copyright © 2011-2022 走看看